我在选择两列时遇到了麻烦,每列都有不同的条件
第一张桌子(主)
id_main |Title
---------------
1 |Title1
2 |Title2
第二张桌子(人)
id_psn | id_main | Name | status
-------------------------------
1 | 1 | Tedy | 1
2 | 1 | john | 2
3 | 2 | lisa | 1
4 | 2 | khan | 2
第二个表的id_main是外键形式表的第一个主键。我希望选择查询产生2列(person1和person2)person1包含状态为1且name2为2的名称。它应产生这样的表
id_main | title | person1 | person2
------------------------------------
1 | title1 | Tedy | john
2 | titl2 | Lisa | khan
ive尝试过这样的查询
SELECT main.id_main ,main.title,
(SELECT person.name where person.status = 1) as 'person1',
(SELECT bap.nama where person.status= 2) as 'person2'
FROM main
JOIN person on main.id_main = person.id_main
并不能像我想要的那样工作。它产生像这样
id_main | title | Person1 | person2
-----------------------------------
1 | title1 | Tedy | NULL
1 | title1 | NULL | john
2 | title2 | Lisa | NULL
2 | title2 | NULL | khan
希望任何人都可以解决这个问题
答案 0 :(得分:1)
SELECT a.id_main,
b.Title AS title,
MAX( CASE WHEN a.status = 1 THEN a.Name ELSE NULL END ) AS person1,
MAX( CASE WHEN a.status = 2 THEN a.Name ELSE NULL END ) AS person2
FROM person a
INNER JOIN
main b
ON a.id_main = b.id_main
GROUP BY a.id_main,b.Title;