SQL从一个表中选择出现的所有记录<另一次是3次

时间:2012-03-24 15:38:13

标签: mysql sql

我有两张桌子:

Event
+----------+---------+--------------+
| event_id | name    | date         |
+----------+------+-----------------+
| 1        | Event 1 | 26/03/2012   |
+----------+------+-----------------+
| 2        | Event 2 | 27/03/2012   |
+----------+------+-----------------+

Reservation
+----------------+------------+--------------+
| reservation_id | date       | themed_id    |
+----------------+------------+--------------+
| 1              | 26/03/2012 | 1            |
+----------------+------------+--------------+
| 2              | 26/03/2012 | 1            |
+----------------+------------+--------------+
| 3              | 27/03/2012 | 2            |
+----------------+------------+--------------+
| 4              | 26/03/2012 | 1            |
+----------------+------------+--------------+

如何在预订表中显示少于3次的所有事件。

输出将是:

+----------+---------+--------------+
| event_id | name    | date         |
+----------+------+-----------------+
| 2        | Event 2 | 27/03/2012   |
+----------+------+-----------------+

因为事件二只在预约中出现过一次

感谢

2 个答案:

答案 0 :(得分:1)

我在猜Event.event_id = Reservation.themed_id?如果是这样的话:

修改:更改为LEFT JOIN以包含0次预订的活动。

SELECT
    Event.event_id,
    Event.name,
    Event.date
FROM
    Event
LEFT JOIN Reservation ON Event.event_id = Reservation.themed_id
GROUP BY
    Event.event_id
HAVING
    COUNT(DISTINCT Reservation.reservation_id) < 3

答案 1 :(得分:1)

SELECT *
FROM Event
WHERE event_id IN (
SELECT themed_id
FROM Reservation
GROUP BY themed_id
HAVING COUNT(*) < 3)

我没有测试,但基本的想法就是这个。