1

我有一张桌子_A

|  id  | status1 | status2 | 
+------+---------+---------+
|   1  |     2   |    3    |
+------+---------+---------+
|   2  |     1   |    3    |
+------+---------+---------+

和表_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

4 回答 4

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
于 2013-08-30T18:07:48.530 回答
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;

但是,双连接版本实际上更简单。

于 2013-08-30T18:07:55.353 回答
2

如果您希望列与 完全一致yep, maybenope, maybe则需要GROUP_CONCAT函数

如果您“取消旋转”您的 ,您可以摆脱一个联接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 BYGROUP_CONCAT确保yep出现在前面maybe,并且确保出现在nope前面。maybe

于 2013-08-30T18:13:45.877 回答
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
于 2013-08-30T18:17:51.600 回答