需要 help/explanation 加入查询

Need help/explanation to JOINED query

我有点迷失了我应该做什么样的 SQL 查询来实现我想要的。

假设我有三个 tables :

select * FROM trip;

| trip_id | title  | description 
----------------------------------
| 1       | title1 | desc1       | 
| 2       | title2 | desc2       |
| 3       | title3 | desc3       |
| 4       | title4 | desc4       |
| 5       | title5 | desc5       |
| 6       | title6 | desc6       |

select * FROM weekly_report;

| report_id | trip_id| incident_id
----------------------------------
| 1         | 1      | (null)      | 
| 2         | 1      | (null)      |
| 3         | 1      | 1           |
| 4         | 2      | 2           |
| 5         | 3      | 3           |
| 6         | 3      | (null)      |


select * FROM incident;

| incident_id | error_code | 
----------------------------------
| 1           | 22223      | 
| 2           | 25456      | 
| 3           | 25456      | 

所以为了一点操作知识:

我想在单个查询中(或者如果必须的话,使用子查询)找到至少一周内为 error_code 声明的事件的旅行次数25456".

示例数据的预期结果:2(因为对于行程 2 和行程 3,存在错误代码为 25456 的事件)。

如果需要我可以解释更多,有没有人愿意帮助我?

谢谢,

试试这个:

SELECT w.trip_id
FROM incident i
INNER JOIN weekly_report w ON i.incident_id=w.incident_id
WHERE error_code='25456'

如果你想要计数,那么

SELECT COUNT(w.trip_id)
FROM incident i
INNER JOIN weekly_report w ON i.incident_id=w.incident_id
WHERE error_code='25456'

您需要统计 次相关事件的行程

select count(distinct w.trip_id)
from weekly_report w
inner join incident i
on w.incident_id = i.incident_id
where i.error_code = 25456;