如何从数据库中选择将此新表显示到页面中。我只是从同一张桌子中选择。任何人都可以帮忙吗?
Id | Username | UserType | SpecialId
-------------------------------------
1 | jdoe | Type_A | SP_1
2 | dmatt | Type_A | SP_2
3 | kwill | Type_A | SP_3
4 | kwill_a | Type_B | SP_3
5 | dmatt_a | Type_B | SP_2
6 | dmatt_b | Type_B | SP_2
No | Type_A Username | Type_B Username
-------------------------------------
1 | jdoe | -
2 | dmatt | dmatt_a, dmatt_b
3 | kwill | kwill_a
答案 0 :(得分:2)
我想你可能想要这样做(看起来像一个表格枢轴问题):
select
replace(SpecialId, 'SP_', '') as No,
max(case when UserType = 'Type_A' then UserName else '-' end) as Type_A_UserName,
max(case when UserType = 'Type_B' then UserName else '-' end) as Type_B_UserName
from (
select `UserType`, `SpecialId`, group_concat(UserName) as UserName
from yourtable
group by `UserType`, `SpecialId`) t
group by SpecialId
答案 1 :(得分:1)
这是你在找什么?
SELECT a.id, a.username, GROUP_CONCAT(b.username)
FROM (SELECT * FROM mytable WHERE usertype='Type_A') AS a
LEFT JOIN (SELECT * FROM mytable WHERE usertype='Type_B') AS b
ON a.specialid = b.specialid
这通过将子查询与自联接相结合来实现目标。
答案 2 :(得分:0)
SELECT
ifnull(tabA.UsernameA, '-') AS UsernameA,
ifnull(tabB.UsernameB, '-') AS UsernameB
FROM (
SELECT SpecialId, group_concat(Username) AS UsernameA
FROM tab
WHERE UserType = 'Type_A'
GROUP BY 1
) AS tabA
OUTER JOIN (
SELECT SpecialId, group_concat(Username) AS UsernameB
FROM tab
WHERE UserType = 'Type_B'
GROUP BY 1
) AS tabB ON tabA.SpecialId = tabB.SpecialId