我被困在一个 SQL 查询上,希望你们能帮助我。
我有 2 张桌子:
EVENTS
event_id (PK)
event_name
ORDERS
order_id (PK)
event_id (FK)
我正在尝试对这些表执行以下查询:
SELECT
e.event_id,
e.name,
COUNT(o.event_id) AS booked
FROM
events AS e
INNER JOIN
orders AS o
ON
e.event_id = o.event_id
WHERE
e.event_id IN (1, 2, 3)
问题是我得到的结果是:
+----------+------+--------+
| event_id | name | booked |
+----------+------+--------+
| NULL | NULL | 0 |
+----------+------+--------+
但是当我运行 3 个单独的查询时:
WHERE e.event_id IN (1)
WHERE e.event_id IN (2)
WHERE e.event_id IN (3)
我得到了我想要的结果:
+----------+-------+--------+
| event_id | name | booked |
+----------+-------+--------+
| 1 | Test1 | 0 |
+----------+-------+--------+
+----------+-------+--------+
| event_id | name | booked |
+----------+-------+--------+
| 2 | Test2 | 0 |
+----------+-------+--------+
+----------+-------+--------+
| event_id | name | booked |
+----------+-------+--------+
| 3 | Test3 | 0 |
+----------+-------+--------+
我究竟做错了什么?有没有办法只使用一个查询并获得:
+----------+-------+--------+
| event_id | name | booked |
+----------+-------+--------+
| 1 | Test1 | 0 |
+----------+-------+--------+
| 2 | Test2 | 0 |
+----------+-------+--------+
| 3 | Test3 | 0 |
+----------+-------+--------+
请帮忙。
更新:当我运行时:
SELECT
e.event_id,
e.name,
COUNT(o.event_id) AS booked
FROM
events AS e
LEFT JOIN
orders AS o
ON
e.event_id = o.event_id
WHERE
e.event_id IN (1, 2, 3)
我只得到:
+----------+-------+--------+
| event_id | name | booked |
+----------+-------+--------+
| 1 | Test1 | 0 |
+----------+-------+--------+