我有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 =
=========================================================================
我需要运行什么查询。
由于
答案 0 :(得分: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
但是如果你有一个未知数量的key
值,那么你将需要使用预准备语句o创建动态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;
结果:
| ID | NAME | EMAIL | AGE | TELE |
------------------------------------------
| 1 | David | d@d.com | 18 | 123456798 |
两者都会产生相同的结果,但是准备好的语句版本会在运行时生成key
值列表。
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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(好像它是几个表),每次只获取与某个键匹配的值。然后,对于我感兴趣的值,我只为每个值选择了相应的别名,并相应地命名了列。