获取所选项目和未选择

时间:2012-03-09 16:43:50

标签: mysql sql database

我想找出哪些项目被选中,任何未被选中的项目变为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 |
+------------+------+----------+----------+

我希望结果显示如下:

+------------+------+----------+----------+
| 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 |
+------------+------+----------+----------+

3 个答案:

答案 0 :(得分:1)

由于查询中的UNION,您的行会重复。实际上,您的整个查询都是倒退的 - 您正在尝试获取所有食物类型的列表,并在指定商店中列出指示符。

请改为尝试:

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 :(得分: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

答案 2 :(得分:0)

我不确定这个答案是否比Mark Ba​​nnister提供的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

如果食品只能为任何给定商店选择一次,那么“选定”字段和GROUP BY是多余的。