0

表1

+----+-----+
| 编号 | 关键 |
+----+-----+
| 1 | 一个 |
| 2 | 乙 |
| 3 | c |
+----+-----+

表2

+----+----------+--------+
| 编号 | tbl1_id | 价值 |
+----+----------+--------+
| 1 | 1 | d |
| 2 | 2 | 电子|
| 3 | 2 | f |
| 4 | 3 | 克 |
| 5 | 3 | h |
| 6 | 3 | 我 |
+----+----------+--------+

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

+----+--------+------+------+------+
| 编号 | 关键 | val0 | val1 | val2 |
+----+--------+------+------+------+
| 1 | 一个 | d | 空 | 空 |
| 2 | 乙 | 电子| f | 空 |
| 3 | c | 克 | h | 我 |
+----+--------+------+------+------+
4

3 回答 3

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 
于 2012-05-17T17:25:26.317 回答
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
于 2012-05-17T17:23:21.937 回答
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

在此处输入图像描述

于 2012-05-21T16:41:15.870 回答