0

tbl1

+ ---- + ----- +
| id | キー|
+ ---- + ----- +
| 1 | a |
| 2 | b |
| 3 | c |
+ ---- + ----- +

tbl2

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

どうすればこの結果を得ることができますか?

+ ---- + ------- + ------ + ------ + ------ +
| id | キー| val0 | val1 | val2 |
+ ---- + ------- + ------ + ------ + ------ +
| 1 | a | d | NULL | NULL |
| 2 | b | e | f | NULL |
| 3 | c | g | 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

Plsはこれを試してみてください、非常によくチェックしてください、

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 に答える
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 に答える