MySQL /如何将几行连接到一个

时间:2012-05-17 17:18:54

标签: mysql

TBL1

+----+-----+
| id | key |
+----+-----+
| 1  | a   |
| 2  | b   |
| 3  | c   |
+----+-----+

TBL2

+----+----------+-------+
| id |  tbl1_id | value |
+----+----------+-------+
| 1  |  1       | d     |
| 2  |  2       | e     |
| 3  |  2       | f     |
| 4  |  3       | g     |
| 5  |  3       | h     |
| 6  |  3       | i     |
+----+----------+-------+

我怎样才能得到这个结果?

+----+-------+------+------+------+
| id | key   | val0 | val1 | val2 |
+----+-------+------+------+------+
| 1  | a     | d    | NULL | NULL |
| 2  | b     | e    | f    | NULL |
| 3  | c     | g    | h    | i    |
+----+-------+------+------+------+

3 个答案:

答案 0 :(得分:0)

使用表和列别名:

SELECT a.id, a.title, t0.value val0, t1.value val1, t2.value val2
FROM tbl1 a
LEFT JOIN tbl2 t0
ON a.id = t0.tbl1_id
LEFT JOIN tbl2 t1
ON a.id = t1.tbl1_id
LEFT JOIN tbl2 t2
ON a.id = t2.tbl1_id

答案 1 :(得分:0)

SELECT a.id, a.key as title, b.value as val0, c.value as val1, d.value as val2
FROM tbl1 as a LEFT JOIN tbl2 as b ON a.id = b.tbl1_id 
               LEFT JOIN tbl2 as c ON a.id = c.tbl1_id 
               LEFT JOIN tbl2 as d ON a.id = d.tbl1_id 

答案 2 :(得分:0)

请尝试一下,检查得非常好,

select distinct(t1.id) as id, t1.key as keyValue, 
(select t2.value from tbl2 t2 where t1.id=t2.tbl1_id and t2.id=(select min(t3.id)
from tbl2 t3 where t3.tbl1_id=t1.id) ) as val0,
(select t2.value from tbl2 t2 where t1.id=t2.tbl1_id and
t2.id=(select t3.id from tbl2 t3 where t3.tbl1_id=t1.id order by t3.id limit 1, 1) ) as val1,
(select t2.value from tbl2 t2 where t1.id=t2.tbl1_id and
t2.id=(select t3.id from tbl2 t3 where t3.tbl1_id=t1.id order by t3.id limit 2, 1) ) as val2
from tbl1 t1

enter image description here