从具有相同字段名称的连接表返回一行

时间:2013-05-18 12:41:58

标签: mysql pivot

阻止:

-------------
| id | name |
-------------
| 1  | test|
-------------

阻止关系坐标

-------------
| id | blockid| coordid
-------------
| 1  | 1   | 1
 -------------
| 1  | 1   | 2
 -------------
 | 1  | 1   | 3
 -------------

阻止坐标

    -------------
    | id | name| type
    -------------
    | 1  | North   | N
     -------------
    | 2  | East   | E
     -------------
     | 3  | South   | S
     -------------

现在我想加入这个表,并在这一行中得到这样的结果 而且结果表的标题也不太重要,只是从这个字段的最后一个表中放入

所有块表与coords表有3个关系

    -------------
    name| NORTH | EAST | SOUTH
    -------------
    test | North | East | South

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
  b.name,
  MAX(CASE WHEN type = 'N' THEN c.name END) AS North,
  MAX(CASE WHEN type = 'E' THEN c.name END) AS EAST,
  MAX(CASE WHEN type = 'S' THEN c.name END) AS SOUTH
FROM block AS b
INNER JOIN block_relation_coords AS r ON b.id = r.blockid
INNER JOIN block_coords          AS c ON c.id = r.coordid
GROUP BY b.name;

请在此处查看:

这会给你:

| NAME | NORTH | EAST | SOUTH |
-------------------------------
| test | North | East | South |

答案 1 :(得分:1)

您需要创建一个数据透视表...此页面为您提供了更多有关它的信息:

http://en.wikibooks.org/wiki/MySQL/Pivot_table

希望它有所帮助。