我正在尝试创建一个查询,向我显示2个表之间的合并数据
当前的表格如下:
person:ID,
Name,
Age
Form
ID,
Person_ID,
question,
answer
Example data would be
1 |Brandon| 55
2 |John |88
3 |Bob| 100
Form:
1 |1 |do you have diabetes |Y
2 |1 |do you take medications| Y
3 |1| how many times a week |7
4 |2|do you have diabetes |N
我尝试过以下操作:
SELECT
p.Name
er1.answer,
er2.answer,
er3.answer
from person p
LEFT JOIN form er1 ON p.ID = er1.Person_ID
LEFT JOIN form er2 ON p.ID = er2.Person_ID
LEFT JOIN form er3 ON p.ID = er3.Person_ID
where er1.question='do you have diabetes'
and er2.question='do you take medications'
and er3.question='how many times a week'
问题是第2个人没有出现,因为他们回答“否”,数据库没有回答其他2个问题。有没有一种方法可以让查询搜索并提取数据,如果不存在,则在那里只有一个空值。
答案 0 :(得分:1)
移动ON
子句中的条件并删除WHERE
子句:
SELECT
p.Name,
er1.answer,
er2.answer,
er3.answer
from person p
LEFT JOIN form er1 ON p.ID = er1.Person_ID AND er1.question='do you have diabetes'
LEFT JOIN form er2 ON p.ID = er2.Person_ID AND er2.question='do you take medications'
LEFT JOIN form er3 ON p.ID = er3.Person_ID AND er3.question='how many times a week'
最好给列起别名:
SELECT
p.Name,
er1.answer as `do you have diabetes`,
er2.answer as `do you take medications`,
er3.answer as `how many times a week`
from person p
LEFT JOIN form er1 ON p.ID = er1.Person_ID AND er1.question='do you have diabetes'
LEFT JOIN form er2 ON p.ID = er2.Person_ID AND er2.question='do you take medications'
LEFT JOIN form er3 ON p.ID = er3.Person_ID AND er3.question='how many times a week'
请参见demo。
结果:
| Name | do you have diabetes | do you take medications | how many times a week |
| ------- | -------------------- | ----------------------- | --------------------- |
| Brandon | Y | Y | 7 |
| John | N | | |
| Bob | | | |
现在考虑通过条件聚合获得所需结果的另一种方法:
select
p.Name,
max(case question when 'do you have diabetes' then answer end) as `do you have diabetes`,
max(case question when 'do you take medications' then answer end) as `do you take medications`,
max(case question when 'do you have diabetes' then answer end) as `how many times a week`
from person p LEFT JOIN form f ON p.ID = f.Person_ID
group by p.ID, p.Name
请参见demo。