gpt4 book ai didi

mysql - 使用 COUNT() 跨 2 个表执行 INNER JOIN

转载 作者:行者123 更新时间:2023-11-29 04:24:13 24 4
gpt4 key购买 nike

我被一个 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 |
+----------+-------+--------+

最佳答案

您应该使用 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

要进一步了解有关联接的更多信息,请访问以下链接:

关于mysql - 使用 COUNT() 跨 2 个表执行 INNER JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15183377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com