如何避免在friends上复制我仍然可以得到两个bob而不是一个bob
我的桌子设置:
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255)
);
INSERT INTO users (id, name)
VALUES (1, "Gregor"),
(2, "Liza"),
(3, "Matt"),
(4, "Tim"),
(5, "Lance"),
(6, "Bob");
CREATE TABLE committee(
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
friend_id INT,
member_id INT,
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`),
FOREIGN KEY (`member_id`) REFERENCES `users` (`id`)
);
INSERT INTO committee (user_id, friend_id, member_id)
VALUES (3, 5, 1),
(4, 5, 1),
(3, 6, 2),
(3, 6, 2),
(4, 6, 2);我使用的查询:
SELECT DISTINCT u.name,
GROUP_CONCAT(f.name) AS friends
FROM committee c
INNER JOIN users u ON (u.id = c.user_id)
INNER JOIN committee c2 ON c2.user_id = c.user_id
INNER JOIN users AS f ON (f.id = c2.friend_id)
WHERE (c.member_id = 1)
GROUP BY u.id;目前的结果:
name friends
Matt Lance,Bob,Bob
Tim Lance,Bob我所期望的:
name friends
Matt Lance,Bob
Tim Lance,Bob发布于 2022-02-05 15:31:03
您只需要在DISTINCT中使用GROUP_CONCAT():
SELECT u.name,
GROUP_CONCAT(DISTINCT f.name) AS friends
................................................请注意,SELECT DISTINCT ...在查询中没有意义,因为您使用的是GROUP BY,它为每个用户返回不同的行。
见演示。
发布于 2022-02-05 15:31:11
您有不同的u.name,而不是f.name
尝尝这个
SELECT u.name,
GROUP_CONCAT(distinct f.name) AS friends
FROM committee c
INNER JOIN users u ON (u.id = c.user_id)
INNER JOIN committee c2 ON c2.user_id = c.user_id
INNER JOIN users AS f ON (f.id = c2.friend_id)
WHERE (c.member_id = 1)
GROUP BY u.name;https://stackoverflow.com/questions/70999402
复制相似问题