2012-03-09 122 views
1

我想找出選擇什麼項目,什麼沒被選中成爲0入門選定項目,沒有選擇

這是列表框(或下拉菜單)是有用的,什麼是強調它的意思是它已經加入(LEFT JOIN)

我不能讓SQL工作:

SELECT StoreID, ft.id, name, count(1) as Selected 
FROM `store_food_type` AS sft 
    LEFT JOIN food_type AS ft 
     ON ft.id = sft.food_type_id 
WHERE StoreID = 17633 
GROUP BY ft.id 

UNION 

SELECT 0, ft.id, name, 0 as Selected FROM food_type AS ft 

編輯:它並沒有產生一個錯誤,它顯示的結果,但name是重複的,我不想

它看起來是這樣的:

+------------+------+----------+----------+ 
| StoreID | id | name  | Selected | 
+------------+------+----------+----------+ 
|  17633 | 1 | Indian |  1 | 
|  17633 | 8 | American |  1 | 
|   0 | 1 | Indian |  0 | 
|   0 | 2 | English |  0 | 
|   0 | 25 | Kurdish |  0 | 
|   0 | 5 | Chinese |  0 | 
|   0 | 7 | Turkish |  0 | 
|   0 | 8 | American |  0 | 
+------------+------+----------+----------+ 

我想要的結果出現這樣的:因爲在你查詢UNION

+------------+------+----------+----------+ 
| StoreID | id | name  | Selected | 
+------------+------+----------+----------+ 
|  17633 | 1 | Indian |  1 | 
|  17633 | 8 | American |  1 | 
|   0 | 25 | Kurdish |  0 | 
|   0 | 5 | Chinese |  0 | 
|   0 | 7 | Turkish |  0 | 
|   0 | 8 | American |  0 | 
+------------+------+----------+----------+ 
+1

此查詢以何種方式失效?它是否產生錯誤,是否運行沒有錯誤,但不選擇行或返回錯誤的行? – 2012-03-09 16:57:11

+0

@MarkBannister我已經更新了我的問題。 – 2012-03-09 17:07:13

+0

同一家商店可以多次選擇食物嗎? – Griffin 2012-03-09 17:57:54

回答

1

你行得到複製。事實上,你的整個查詢是反向的 - 你試圖獲得所有食物類型的列表,並且如果它們被列在給定商店中,則有指示符。

試試這個:

SELECT ft.id, ft.name, COALESCE(sft.storeId, 0) as storeId, 
     CASE WHEN sft.storeId IS NOT NULL THEN '1' 
      ELSE '0' END as selected 
FROM food_type a ft 
LEFT JOIN store_food_type as sft 
ON sft.food_type_id = ft.id 
AND sft.storeId = 17633 

雖然你不嚴格需要selected列,因爲你可以簡單地測試結果列storeId是否0。

1

也許最簡單的方法是將集團的結果從被聯合查詢 - 就像這樣:

SELECT MAX(StoreID) StoreID, id, MAX(name) name, MAX(Selected) Selected FROM 
(SELECT StoreID, ft.id, name, count(1) as Selected 
FROM `store_food_type` AS sft 
    LEFT JOIN food_type AS ft 
     ON ft.id = sft.food_type_id 
WHERE StoreID = 17633 
GROUP BY ft.id 
UNION 
SELECT 0, ft.id, name, 0 as Selected FROM food_type AS ft) sq 
GROUP BY id 
0

我不知道這個答案是比任何由馬克·班尼斯特提供的UNION選擇更好的,但它是另一種方式來做到這一點。

SELECT sft.storeid, ft.id, ft.name, count(sft.storeid) selected 
FROM store_food_type sft 
     FULL JOIN food_type ft ON ft.id = sft.food_type_id 
WHERE sft.storeid = 17633 or sft.storeid is null 
GROUP BY ft.id, ft.name, sft.storeid 

如果一個食品只能在任何給定的商店中選擇一次,那麼「selected」字段和GROUP BY是多餘的。

+0

我覺得MySQL不支持'FULL JOIN' – 2012-03-09 21:14:40