2013-07-25 53 views
0

我有三個表格:類別,故事和術語。條款表存儲類別和故事的關係。每個故事可以有一個或多個類別分配。我想只爲故事選擇一個類別。我在story_id上使用DISTINCT子句,但它不起作用。請看下面的查詢從一對多表格中選擇不同的值

SELECT DISTINCT S.story_id, C.cat_id 
    FROM stories S JOIN terms C USING(story_id) 
LIMIT 3; 

,並導致

 
+----------+--------+ 
| story_id | cat_id | 
+----------+--------+ 
|  115 |  17 | 
|  115 |  20 | 
|  115 |  21 | 
+----------+--------+ 
3 rows in set (0.00 sec) 

任何線索爲什麼不拿起唯一story_id?

回答

3

...任何線索,爲什麼不拿起唯一story_id?

因爲DISTINCT適用所有列在條款SELECT而不是一個單獨的列不退還獨特story_id。


既然你...要選擇只有一個類的故事...你可以使用一個聚合函數MIN()MAX()GROUP BY

SELECT s.story_id, MIN(c.cat_id) cat_id 
    FROM stories s JOIN terms c 
    ON s.story_id = c.story_id 
GROUP BY s.story_id 

現在既然你只返回story_idcat_id你甚至不需要加入storiesterms

SELECT story_id, MIN(cat_id) cat_id 
    FROM terms 
GROUP BY story_id 

這裏是SQLFiddle演示

0

試試這個:

SELECT DISTINCT S.story_id, C.cat_id FROM stories AS S 
INNER JOIN terms AS C ON(S.cat_id = C.cat_id) 
GROUP BY S.story_id 
+0

切勿混用'的解釋DISTINCT'和'GROUP BY' – peterm

1

DISTINCT S.story_id, C.cat_id將同時考慮story_id和CAT_ID作爲一個實體並刪除重複。如果你需要得到不同story_id那麼你可以試試下面

SELECT S.story_id, C.cat_id FROM stories AS S 
INNER JOIN terms AS C ON(S.cat_id = C.cat_id) 
GROUP BY S.story_id 
HAVING COUNT(*) >=1 
+0

謝謝 – Maximus

相關問題