[英]SQL - Combine a select * query with select 1
I'm trying to combine data from two tables in one result. 我正在尝试将两个表中的数据合并到一个结果中。 With simplified example-tables, this is what I want to get in result:
使用简化的示例表,这就是我想要得到的结果:
ID Text Choice
--------------------------------
1 My first choice 0
2 My second choice 0
3 My third choice 1
from the two tables persons and choosen 从两个表的人中选择
'Persons': “人员”:
ID Name Age
-------------------
1 Adam 22
2 Scott 25
3 Tom 28
'Choices': “选择”:
ID Text
----------------------
1 My first choice
2 My second choice
3 My third choice
'Choices_made': 'Choices_made':
Person_ID Choice_ID
----------------------
2 3
I have tried some different queries, but not found the right one. 我尝试了一些不同的查询,但没有找到正确的查询。 I got stuck when trying this query:
我在尝试此查询时陷入困境:
SELECT * FROM (
(SELECT * FROM Choices) t1
UNION
(SELECT 1 as Choice FROM Choices_made WHERE Person_ID=2) t2
) t_union
... which does not work. ...这不起作用。 It causes error #1064 - You have an error in your SQL syntax.
它导致错误#1064-您的SQL语法有错误。
Any suggestions on how I can accomplish the wanted result? 关于如何实现所需结果的任何建议?
You can try the next query 您可以尝试下一个查询
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
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
You could use left join then use case when when setting the 3rd field to 1 or zero 将第三个字段设置为1或零时,可以使用左联接,然后用例
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.