我有一个table_A
| id | status1 | status2 |
+------+---------+---------+
| 1 | 2 | 3 |
+------+---------+---------+
| 2 | 1 | 3 |
+------+---------+---------+
和table_B
| id | name |
+------+---------+
| 1 | yep |
+------+---------+
| 2 | nope |
+------+---------+
| 3 | maybe |
+------+---------+
如何让输出看起来像这样?
1 =不,也许;
2 =是的,也许
我试过这样的事情:
SELECT * FROM table_A a
LEFT JOIN table_B b
ON a.status1= b.id AND a.status2= b.id"
答案 0 :(得分:2)
你也可以这样做:
SELECT * FROM table_A a
LEFT JOIN table_B b ON a.status1= b.id
LEFT JOIN table_B bTmp ON a.status2= bTmp.id
答案 1 :(得分:2)
您想要进行两个连接,每个状态字段一个:
SELECT a.id, b1.name as name1, b2.name
FROM table_A a LEFT JOIN
table_B b1
ON a.status1 = b1.id LEFT JOIN
table_B b2
on a.status2= b2.id;
编辑:
为娱乐起见,您可以通过一次加入和聚合来完成此操作:
select a.id,
max(case when a.status1 = b.id then b.name end) as name1,
max(case when a.status2 = b.id then b.name end) as name2
from table_A a left join
table_B b
on b.id in (a.status1, a.status2)
group by a.id;
但是,双连接版本实际上更简单。
答案 2 :(得分:2)
如果您希望列完全属于yep, maybe
和nope, maybe
,则需要GROUP_CONCAT
function。
如果你“解锁”你的table_a
,你就可以逃脱一个联接,这就是我答案中的子查询:
SELECT
a.id,
GROUP_CONCAT(b.name ORDER BY b.name DESC)
FROM (
SELECT id, status1 AS stat_id FROM table_a
UNION SELECT id, status2 FROM table_a
) a
INNER JOIN table_b b ON a.stat_id = b.id
GROUP BY a.id;
ORDER BY
中的GROUP_CONCAT
可确保yep
出现在maybe
之前nope
出现在逗号分隔列表中的maybe
之前
答案 3 :(得分:0)
select a.id, b1.name, b2.name from tableB as b1
inner join TableA as a
on b1.id = a.status1
inner join TableB as b2
on b2.id = a.status2