2012-03-24 30 views
0

選擇從一個表中出現的所有記錄<3次我有兩個表: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 | 
+----------+------+-----------------+ 

隨着事件的兩個在預訂只出現過一次

感謝

+1

你有沒有先試過任何東西?我們在這裏爲您提供幫助,而不是給您一個完整的書面解決方案。 – Bojangles 2012-03-24 15:39:56

回答

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

我沒有測試過,但基本思路是這樣的。

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