从左连接mysql获取两列中的两行

时间:2013-11-09 08:26:58

标签: php mysql

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

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

请帮帮我们!

1 个答案:

答案 0 :(得分:0)

你应该使用聚合函数,它使用“group by”的多行,也可以在“group by”下移动table1.name。

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;