SQL - 将select *查询与select 1组合

时间:2015-07-13 23:45:50

标签: mysql sql select

我试图在一个结果中组合来自两个表的数据。使用简化的示例表,这就是我想要得到的结果:

ID    Text                Choice
--------------------------------
1     My first choice     0
2     My second choice    0
3     My third choice     1

来自两个人并选择

'人':

ID      Name    Age
-------------------
1       Adam    22
2       Scott   25
3       Tom     28

'选择':

ID    Text
----------------------
1     My first choice
2     My second choice
3     My third choice

' Choices_made':

Person_ID    Choice_ID
----------------------
2            3

我尝试了一些不同的查询,但找不到合适的查询。我在尝试此查询时遇到困难:

SELECT * FROM (
(SELECT * FROM Choices) t1
UNION
(SELECT 1 as Choice FROM Choices_made WHERE Person_ID=2) t2
) t_union

......这不起作用。它会导致错误#1064 - 您的SQL语法出错。

关于如何完成想要的结果的任何建议?

3 个答案:

答案 0 :(得分:2)

您可以尝试下一个查询

SELECT Choices.*
      ,IF(Choices_made.Choice_ID IS NULL, 0, 1) AS Choice
FROM Choices
     LEFT JOIN Choices_made ON Choices_made.Choice_ID = Choices.ID AND Choices_made.Person_ID = @PersonID

答案 1 :(得分:1)

SELECT c.id,
       c.text, 
       cm.Choice_ID = c.id as persons_choice
FROM Choices c
LEFT JOIN Choices_made cm on cm.Choice_ID = c.id
                         and cm.Person_ID = 2

答案 2 :(得分:0)

您可以使用左连接 然后在将第3个字段设置为1或0时使用大小写

SELECT p.id as , c.text, 
CASE 
WHEN cm.choice_id <> 0 then 1
ELSE 
0
END
as Choice
from persons as p
left join choices as c on c.id = p.id
left join choices_made as cm on cm.personid = p.id