1

我有一张看起来像这样的桌子:

表 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    |
+-----+------------+-----------+------------+

这里的关系是id表1中的table1_idin对应表2中的in。

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

+----+---------+---------+-------------+-----------+-----------+
| 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   | 

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

先感谢您。

4

2 回答 2

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 

希望这可以帮助!

于 2012-06-27T17:50:55.457 回答
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;
于 2012-06-27T18:19:26.750 回答