我有两个 MySQL 表,users
和supervisors
. 在这个简化的示例中,users
只有一个 ID 和一个用户名,并且supervisors
是一个将两个用户链接在一起的表。
我想构建一个返回两列的查询 - 一个用户名和他们主管的用户名列表。
我已经弄清楚如何通过此查询仅使用主管的 ID 来完成此操作:
SELECT U.username, GROUP_CONCAT(S.supervisorId) AS Supervisors FROM users AS U LEFT JOIN `supervisors` AS S ON S.userId=U.userID WHERE 1 GROUP BY U.userID;
例如,它返回1,3
给史蒂夫的主管。相反,我希望它返回Carol, Dave
(最好按字母顺序在空格后加逗号,但如有必要,我可以稍后处理)。
这可能吗?我不确定如何实现它。谢谢!
CREATE TABLE IF NOT EXISTS `users` (
`userId` int(6) unsigned NOT NULL,
`username` varchar(200) NOT NULL,
PRIMARY KEY (`userId`)
) DEFAULT CHARSET=utf8;
INSERT INTO `users` (`userId`, `username`) VALUES
('1', 'Dave'),
('2', 'Jane'),
('3', 'Carol'),
('4', 'Steve');
CREATE TABLE IF NOT EXISTS `supervisors` (
`supervisorId` int(6) unsigned NOT NULL,
`userId` int(6) NOT NULL,
PRIMARY KEY (`supervisorId`,`userId`)
) DEFAULT CHARSET=utf8;
INSERT INTO `supervisors` (`supervisorId`, `userId`) VALUES
('1', '2'),
('1', '3'),
('1', '4'),
('3', '4');
1 个回答