如何编写返回包含Yes和No的列的SQL查询?

时间:2019-04-28 11:16:04

标签: mysql

我想编写一个SQL查询,该查询返回一个名为Fav_Blue的列的所有人的姓名,该列包含Yes或No,具体取决于该人是否将Blue作为喜好的颜色。

有2个表:

  • 人(ID,姓名)

  • 收藏夹颜色(person_ID,颜色)

在“收藏夹颜色”表中,包含以下行:

  • (1,蓝色)
  • (1,红色)
  • (1,黑色)
  • (2,绿色)
  • (3,蓝色)

我尝试了以下查询:

    SELECT DISTINCT CASE WHEN FC.Colour = "Blue" THEN  "Yes"
    ELSE "No"
    END AS Fav_Blue, P.Name
    FROM People P, Favourite_Colour FC
    WHERE P.ID = FC.person_ID 

输出中的问题是我有两行,其中Mark分别显示Yes和No:

  • (马克,是)
  • (标记,否)
  • (萨拉,不)
  • (埃里克,是)

因为ID为1的人最喜欢蓝色和其他颜色。

我只想显示(标记,是)行,而不显示其他行。

要实现此目的,我必须更改查询中的什么内容?

3 个答案:

答案 0 :(得分:0)

您可以在适当的位置使用

来避免案件突出
SELECT   "Yes" AS Fav_Blue, P.Name 
FROM People P
INNER JOIN Favourite_Colour FC ON P.ID = FC.person_ID 
WHERE FC.Colour = "Blue"

否则,请使用CASE将案例添加到where

SELECT DISTINCT CASE WHEN FC.Colour = "Blue" THEN  "Yes"
ELSE "No"
END AS Fav_Blue, P.Name
FROM People P
INNER JOIN Favourite_Colour FC ON P.ID = FC.person_ID 
WHERE CASE WHEN FC.Colour = "Blue" THEN  "Yes"
                ELSE "No"
               END = 'YES'

以及还有其他喜欢的颜色的人

SELECT   "Yes" AS Fav_Blue, P.Name 
FROM People P
INNER JOIN Favourite_Colour FC ON P.ID = FC.FC.person_ID  
WHERE FC.Colour = "Blue"
INNER JOIN (
  select  person_ID 
  from  Favourite_Colour
  group by person_ID
  having count(*)>1
) t ON t.person_ID =  P.ID 

答案 1 :(得分:0)

SELECT People.Name,
       (CASE when (Favourite_Colour.Color = "Blue") 
 THEN
      "Yes" 
 ELSE
      "No" 
 END) as Fav_Blue
FROM People LEFT JOIN Favourite_Colour 
ON People.id = Favourite_Colour.person_ID;

答案 2 :(得分:0)

执行此操作的一种方法是为每个人SUMColour = 'Blue'的所有Favourite_Colour值。由于MySQL在数值上下文中将布尔表达式视为1(真)或0(假),因此,如果用户将SUM作为喜欢的颜色,则此Blue仅大于0:

SELECT p.ID, p.Name, 
       CASE WHEN SUM(F.Colour = 'Blue') > 0 THEN 'Yes' ELSE 'No' END AS Fav_Blue
FROM People p
LEFT Join Favourite_Colour F ON F.person_ID = p.ID
GROUP BY p.ID, p.Name

您还可以使用EXISTS表达式来检查Blue表中某人是否存在Favourite_Colour

SELECT p.ID, p.NAME,
       CASE WHEN EXISTS (SELECT * FROM Favourite_Colour F WHERE Colour = 'Blue' AND F.person_ID = p.ID) THEN 'Yes' ELSE 'No' END AS Fav_Blue
FROM People p

输出(我可以随意给第2和第3个人分配名称):

ID  Name    Fav_Blue
1   Mark    Yes
2   Bill    No
3   Fred    Yes

Demo on dbfiddle