我有一個SQL查詢的問題,返回的結果集不是我的預期。SQL查詢語句表連接
我有這三個表,我試圖涉及。
events_detail
__________________
| ID | start_date |
| 1 | 2012-08-09 |
| 2 | 2013-02-13 |
| 3 | 2012-12-12 |
| 4 | 2013-01-21 |
| 5 | 2012-12-25 |
-------------------
其中ID是主鍵
events_category_relationship
__________________________
| ID | event_id | cat_id |
| 1 | 1 | 1 |
| 2 | 2 | 4 |
| 3 | 3 | 2 |
| 4 | 4 | 2 |
| 5 | 5 | 3 |
--------------------------
其中ID是主鍵
events_category_detail
__________________________________
| ID | name | description |
| 1 | Europe | Kings and castles! |
| 2 | USA | Freedoms |
| 3 | China | Made in China |
| 4 | UK | Big Brother |
------------------------------------
其中ID是主鍵
我需要做的就是抓住從每個類別只有1個事件,並通過最早的出現日期排序。所以,我應該會在我的結果如下
結果集
________________________________________________________________
| e_id | start_date | c_id | category_name | category_desc |
| 1 | 2012-08-09 | 1 | Europe | Kings and castles! |
| 3 | 2012-12-12 | 2 | USA | Freedoms |
| 5 | 2012-12-25 | 3 | China | Made in China |
| 2 | 2013-02-13 | 4 | UK | Big Brother |
-----------------------------------------------------------------
,我想我的SQL查詢看起來像這樣
SELECT e.id, e.start_date, c.category_name, c.category_desc
FROM events_detail e
JOIN events_category_relationship r ON r.event_id = e.id
JOIN events_category_detail c ON c.id = r.cat_id
ORDER BY date(e.start_date)
這只是加入了3個表,然後返回結果按日期排序。我所堅持的是讓每個類別中只有一個類似上面所需的結果集。我曾嘗試使用DISTINCT c.category_name和GROUP BY c.category_name,但它們都不起作用。
任何幫助或建議將不勝感激。
看一看http://www.xaprb.com /博客/ 2006/12/07 /如何對選擇最firstleastmax行每組在SQL /。這是在這個網站上的類似的線程建議。 – 2013-03-04 18:32:26