我坚持使用SQL查询,我希望你们可以帮助我。
我有两张桌子:
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 |
+----------+-------+--------+
答案 0 :(得分:4)
您应该使用LEFT JOIN
而不是INNER JOIN
,并且不要忘记使用GROUP BY
子句,因为您使用的是聚合函数 COUNT()
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)
GROUP BY e.event_id, e.name
要进一步了解联接,请访问以下链接:
答案 1 :(得分:1)
使用带有if条件的左连接可以做到
SELECT
e.event_id,
e.name,
SUM(IF(o.event_id IS NULL, 0, 1)) 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)
GROUP BY e.event_id, e.name
或者你也可以这样做
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)
GROUP BY e.event_id, e.name