1

可能重复:
带有 3 个表的数据透视表

编辑:对不起,我的一列错了

我有以下表格:

_______________________________________
| ItemID | ItemName | ItemDescription |
|________|__________|_________________|
|   1    |  Alice   |       Foo       |
|________|__________|_________________|
|   2    |   Bob    |       Bar       |
|________|__________|_________________|

________________________
| LinkID | LinkAddress |
|________|_____________|
|   1    |  www.c.com  |
|________|_____________|
|   2    |  www.b.com  |
|________|_____________|
|   3    |  www.a.com  |
|________|_____________|

________________________________________
| AssocID | ItemID | LinkID | LinkType |
|_________|________|________|__________|
|    1    |   1    |   3    | Youtube  |
|_________|________|________|__________|
|    2    |   2    |   2    | Facebook |
|_________|________|________|__________|
|    3    |   2    |   1    | Twitter  |
|_________|________|________|__________|

我正在尝试获取一个 SQL 查询来创建这样的结果:

__________________________________________________________________
| ItemName | ItemDescription | Youtube   | Facebook  |  Twitter  |
|__________|_________________|___________|___________|___________|
|  Alice   |       Foo       |   NULL    |   NULL    | www.a.com |
|__________|_________________|___________|___________|___________|
|   Bob    |       Bar       | www.c.com | www.b.com |   NULL    |
|__________|_________________|___________|___________|___________|

这可能吗?

4

1 回答 1

2
SELECT  a.ItemName, a.ItemDescription,
        MAX(CASE WHEN b.LinkType = 'Youtube' THEN c.LinkAddress ELSE NULL END) youtube,
        MAX(CASE WHEN b.LinkType = 'Facebook' THEN c.LinkAddress ELSE NULL END) Facebook,
        MAX(CASE WHEN b.LinkType = 'Twitter' THEN c.LinkAddress ELSE NULL END) Twitter
FROM    tableName a
        LEFT JOIN tableAssco b
            ON a.ItemID = b.ItemID
        LEFT JOIN tableLinks c
            ON b.LinkID = c.LinkID
GROUP BY a.ItemName, a.ItemDescription

或通过使用Prepared Statements

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN b.LinkType = ''',
      LinkType,
      ''' then c.LinkAddress ELSE NULL end) AS ',
      LinkType
    )
  ) INTO @sql
FROM tableAssco;

SET @sql = CONCAT('SELECT  a.ItemName, a.ItemDescription, ', @sql, ' 
                   FROM    tableName a
                          LEFT JOIN tableAssco b
                              ON a.ItemID = b.ItemID
                          LEFT JOIN tableLinks c
                              ON b.LinkID = c.LinkID
                  GROUP BY a.ItemName, a.ItemDescription');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2012-11-01T16:17:55.127 回答