如何在同一个字段上连接两个ON条件

时间:2013-08-30 18:03:39

标签: mysql join

我有一个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"

4 个答案:

答案 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, maybenope, 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