2012-01-10 101 views
2

事件events_stylesevents_formats表(一個事件可以有衆多的款式和多種格式) 我想篩選其中有一個events_styles加入和events_formats參加活動。因此,查詢應該選擇哪些是特定風格和特定格式的所有事件 - 我嘗試到目前爲止:MySQL的多個多對多連接

SELECT * FROM events 
JOIN events_styles ON events.id = events_styles.event_id 
JOIN events_formats ON events.id = events_formats.format_id 
WHERE events_styles.style_id = 3 AND events_formats.format_id = 1; 

Empty set (0.00 sec) 

SELECT * FROM events_styles 
WHERE events_styles.style_id = 3 
+----------+----------+ 
| event_id | style_id | 
+----------+----------+ 
|  3 |  3 | 
|  2 |  3 | 
|  4 |  3 | 
+----------+----------+ 
3 rows in set (0.00 sec) 

SELECT * FROM events_formats 
WHERE events_formats.format_id = 1  
+----------+-----------+ 
| event_id | format_id | 
+----------+-----------+ 
|  1 |   1 | 
|  3 |   1 | 
|  4 |   1 | 
+----------+-----------+ 
3 rows in set (0.00 sec) 

所以第一個查詢應與ID 4返回事件? 我確定我需要將第二個和第三個查詢合併到一個子查詢中,但是Im不確定語法 - 謝謝

+0

你會踢你自己;你的連接條件events.id = events_formats.format_id應該是events.id = events_formats.event_id – dash 2012-01-10 13:21:20

回答

1

您非常接近!

您的查詢應該是:

SELECT * FROM events 
JOIN events_styles ON events.id = events_styles.event_id  
JOIN events_formats ON events.id = events_formats.event_id 
WHERE events_styles.style_id = 3 
AND events_formats.format_id = 1; 

通過加入對業態編號,而不是EVENT_ID你只會變得事項標識= 1,它具有3沒有correspoding風格的ID就是你出了錯:-)

+0

你的權利 - 我開始踢自己! - 謝謝 – rebelbass 2012-01-10 13:30:03