6

我有两张桌子:

table_a:            table_b
+----+------+    +----+---------+------+
| id | name |    | id | relation| name | 
+----+------+    ++++++---------+------+
| 1  | bob  |    | 1  | friend  | chris|
| 2  | jim  |    | 1  | friend  | jon  |
| 3  | tom  |    | 1  | brother | matt |
+----+------+    | 2  | friend  | sam  |
                 | 2  | parent  | ron  |
                 +----+---------+------+

我想输入一个查询来输出类似

+----+------+------------+---------+--------+
| id | name |friend      | brother | parent |
+----+------+------------+---------+--------+
| 1  | bob  | chris, john| matt    |        |
| 2  | jim  | sam        |         |  ron   |
+----+------+------------+---------+--------+

所以 id 是两个表之间的comman 变量,关系变量具有预设值(朋友、兄弟、父母和其他几种类型),每个 id 的每个关系可以有多个 table_b.name。

这是一项太复杂的任务吗?

4

1 回答 1

4
SELECT a.ID, a.name,
        GROUP_CONCAT(CASE WHEN relation = 'friend' THEN b.name ELSE NULL END) friend,
        GROUP_CONCAT(CASE WHEN relation = 'brother' THEN b.name ELSE NULL END) brother,
        GROUP_CONCAT(CASE WHEN relation = 'parent' THEN b.name ELSE NULL END) parent
FROM  table_a a
        INNER JOIN table_b b
            ON a.id = b.id
GROUP BY a.ID, a.name

SQLFiddle 演示

将来,如果您有任何其他关系,friend, brother, and parent并且不想更改查询,则可以使用准备好的语句

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'GROUP_CONCAT(CASE WHEN relation = ''',
      relation,
      ''' then b.name ELSE NULL end) AS ',
      relation
    )
  ) INTO @sql
FROM table_b;

SET @sql = CONCAT('SELECT a.ID, a.name, ', @sql, ' 
                   FROM  table_a a
                         INNER JOIN table_b b
                             ON a.id = b.id
                   GROUP BY a.ID, a.name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQLFiddle 演示

于 2012-10-23T11:44:09.107 回答