-1

我有两个表格,下面给出了结构和数据。

table1
id, name
1, abc
2, xyz


table2
id, table1_id, type, other_name
1, 1, 1, hello
2, 1, 2, world
3, 2, 1, wonder
4, 2, 2, this world

需要具有以下列的行的结果:

table1.id, table1,name, table2.other_name where table2.type=1, table2.other_name where table2.type=2

我试过了:

SELECT
table1.id, table1,name,
IF(table2.type=1, table2.other_name,NULL) AS current_name,
IF(table2.type=2, table2.other_name,NULL) AS previous_name
FROM table1
LEFT JOIN table2 ON table2.table1_id = table1.id
GROUP BY table1.id;

但它返回如下:

1, abc, hello, NULL
2, xyz, wonder, NULL

而我希望得到如下结果:

1, abc, hello, world
2, xyz, wonder, this world

请帮助伙计们!

4

1 回答 1

0

您应该使用聚合函数,它使用“group by”处理多行,也将 table1.name 移动到“group by”下。

SELECT table1.id, 
       table1.name,
       max(IF(table2.type=1, table2.other_name, NULL)) AS current_name,
       max(IF(table2.type=2, table2.other_name, NULL)) AS previous_name
FROM table1
LEFT JOIN table2 ON table2.table1_id = table1.id
GROUP BY table1.id, table1.name;
于 2013-11-09T10:36:35.220 回答