0

我有 2 张桌子

表格1

===================================
= Id = Name             =  email  =
===================================
= 1  = David            = d@d.com =
===================================

表 2

==================================
= uid = key        =  Value      =
==================================
= 1   = Age        =  18         =
= 1   = Tele       =  0123456798 =
==================================

这个想法是 UID 与 Id 相关以链接表。

我想做的是运行一个 SQL 查询来获得以下输出。

=========================================================================
= Id = Name             =  email  = age        =  Tele                  =
=========================================================================
= 1  = David            = d@d.com = 18         = 012345678              =
=========================================================================

我需要运行什么查询。

谢谢

4

4 回答 4

2

虽然您已经接受了答案,但我发布此答案是为了提供替代解决方案。您正在尝试PIVOT数据,而 MySQL 没有数据透视函数,因此您可以将聚合函数与CASE语句一起使用。

如果您有已知数量的值,则可以对查询进行硬编码:

select t1.id,
    t1.name,
    t1.email,
    MAX(CASE WHEN t2.key='age' THEN t2.value ELSE NULL END) AS age,
    MAX(CASE WHEN t2.key='tele' THEN t2.value ELSE NULL END) AS tele
FROM Table1 t1 
LEFT JOIN Table2 t2 
  ON t1.Id = t2.uid
GROUP BY t1.id, t1.name, t1.email

请参阅带有演示的 SQL Fiddle

但是,如果您有未知数量的key值,那么您将需要使用准备好的语句来创建动态 sql 版本:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when t2.`key` = ''',
      `key`,
      ''' then t2.Value else null end) AS ',
      `key`
    )
  ) INTO @sql
FROM table2;

SET @sql = CONCAT('SELECT t1.id, t1.name, t1.email, ', @sql, ' 
                  FROM table1 t1
                  left join table2 t2
                    on t1.id = t2.uid
                  GROUP BY t1.id, t1.name, t1.email');

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

请参阅带有演示的 SQL Fiddle

结果:

| ID |  NAME |   EMAIL | AGE |      TELE |
------------------------------------------
|  1 | David | d@d.com |  18 | 123456798 |

两者都会产生相同的结果,但准备好的语句版本会key在运行时生成值列表。

于 2012-12-13T18:16:17.547 回答
1
select t1.id,
    t1.name,
    t1.email,
    MAX(CASE WHEN t2.key='age' THEN t2.value ELSE NULL END) AS age,
    MAX(CASE WHEN t2.key='tele' THEN t2.value ELSE NULL END) AS tele
FROM Table1 t1 INNER JOIN Table2 t2 ON t1.Id = t2.uid
GROUP BY t1.id, t1.name, t1.email
于 2012-12-13T17:40:20.143 回答
1

像这样的东西:

select 
  t.Id,
  t.Name, 
  t.Email,
  (select Value from Table2 t2 where t2.uid = t.Id and t2.Key = 'Age') as Age, 
  (select Value from Table2 t2 where t2.uid = t.Id and t2.Key = 'Tele') as Tele 

from Table1 t

如果您事先知道密钥,则上述查询有效。它的名字是未知的,从数据库中获取可用的键名列表:

select distinct Key from Table2
于 2012-12-13T17:40:31.683 回答
1
select
  Id,
  Name,
  email,
  age.Value as age,
  tele.Value as tele
from `Table 1`
left join `Table 2` as age on age.key='Age' and age.uid=Id
left join `Table 2` as tele on tele.key='Tele' and tele.uid=Id
;

我只是多次加入表 2(好像它是几个表),每次只取与某个键匹配的值。然后对于我感兴趣的值,我只需为每个值选择适当的别名并相应地命名列。

于 2012-12-13T17:41:38.577 回答