我有两张桌子:
id | name ----------------------------------------- 1 | abc 2 | def
table1id | nr_name | nr_val ----------------------------------------- 1 | 7 | 123 1 | 9 | 321 2 | 7 | 432
获得此结果需要哪些SQL代码?
id | name | nr7 | nr9 ----------------------------------------- 1 | abc | 123 | 321 2 | def | 432 | 0
nr_name只能是7或9,我无法更改table2的结构 (我稍后会添加更多nr_name类型。)
答案 0 :(得分:1)
试试这个:
sELECT
t1.id,
t1.name,
MAX(CASE WHEN t2.nr_name = 7 THEN t2.nr_val END) AS 'nr7',
MAX(CASE WHEN t2.nr_name = 9 THEN t2.nr_val END) AS 'nr9'
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.id = t2.table1id
WHERE t2.name IN (7, 9)
GROUP BY t1.id, t1.name
答案 1 :(得分:0)
SELECT t1.id,t1.name,
CASE WHEN t2.nr_name = 7 THEN t2.nr_val ELSE 0 END AS 'nr7',
CASE WHEN t2.nr_name = 9 THEN t2.nr_val ELSE 0 END AS 'nr9'
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.id = t2.table1id
WHERE t2.name IN (7,9)
GROUP BY t1.id, t1.name