如何正确格式化此MySQL JOIN语句?

时间:2012-06-27 17:41:13

标签: mysql

我有一张看起来像的表:

表1 - >

+----+--------+--------+
| id |  name  | author |
+----+--------+--------+
| 1  |  First |   Me   |
| 2  | Second |  You   |
+----+--------+--------+

表2 - >

+-----+------------+-----------+------------+
| mid |  table1_id |    key    |    value   |
+-----+------------+-----------+------------+
|  1  |      1     |   desc    |   hello    |
|  2  |      1     | begin_day |   monday   |
|  3  |      1     | end_day   |   tuesday  |
|  4  |      2     |   desc    |   goodbye  |
|  5  |      2     | begin_day |  wednesday |
|  6  |      2     | end_day   |  friday    |
+-----+------------+-----------+------------+

此处的关系是表1中的id对应于表2中的table1_id

我想要获得的输出是......

+----+---------+---------+-------------+-----------+-----------+
| id |  name   |  author |     desc    | begin_day |  end_day  |
+----+---------+---------+-------------+-----------+-----------+
|  1 |  First  |   Me    |    hello    |   monday  |  tuesday  |
|  1 |  Second |   You   |   goodbye   | wednesday |  friday   |
+----+---------+---------+-------------+-----------+-----------+

我尝试了几种不同的联接声明 - 所有这些都是以下的变体。但是,我并不精通MySQL查询。

SELECT * FROM table_1 LEFT JOIN table_2 on table_1.id = table_2.table1_id

哪个产生......

+----+----------+----------+----------+------------+-----------+
| id |    mid   |   name   |  author  |    key     |   value   |
+----+----------+----------+----------+------------+-----------+
| 1  |     1    |   First  |    Me    |    desc    |   hello   |
| 1  |     2    |   First  |    Me    |  begin_day |   monday  |
| 1  |     3    |   First  |    Me    |   end_day  |   tuesday |
| 2  |     4    |   Second |   You    |    desc    |  goodbye  |
| 2  |     5    |   Second |   You    |  begin_day |  wednesday|
| 2  |     6    |   Second |   You    |   end_day  |  friday   | 

显然,遍历此join语句会产生6个结果,表2中每行的1个与表1中的id匹配。如何使用正确的查询语句来避免这种情况?

提前谢谢。

2 个答案:

答案 0 :(得分:2)

如果您知道将要获得的所有列,则可以使用case语句,如下所示:

Select distinct table_1.*, 
case when table_2.key='desc' then value end as desc, 
case when table_2.key='begin_day' then value end as begin_day, 
case when table_2.key='end_day' then value end as end_day
  FROM table_1 LEFT JOIN table_2 on table_1.id = table_2.table1_id 

希望这有帮助!

答案 1 :(得分:0)

SELECT
 table_1.*, 
 MAX(IF(key='desc', value, NULL)) AS 'desc', 
 MAX(IF(key='begin_day', value, NULL)) AS begin_day, 
 MAX(IF(key='end_day', value, NULL)) AS end_day
FROM table_1 
LEFT JOIN table_2 ON (id = table1_id)
GROUP BY id;