1

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

2 回答 2

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

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

于 2013-03-03T07:19:21.413 回答
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

SQL 小提琴演示

于 2013-03-03T07:24:21.397 回答