Mysql DISTINCT gibt immer noch doppelte Werte zurück
P粉369196603
P粉369196603 2024-02-21 13:25:49
0
2
365

Wie man den Aufenthalt vermeidet friends 上重复,我仍然得到两个 bob,而不是只有一个 bob

Mein Tischaufbau:

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);

Die von mir verwendete Abfrage:

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;

Aktuelle Ergebnisse:

name    friends
Matt    Lance,Bob,Bob
Tim Lance,Bob

Meine Erwartungen:

name    friends
Matt    Lance,Bob
Tim Lance,Bob

P粉369196603
P粉369196603

Antworte allen(2)
P粉706038741

您的 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;
P粉714844743

您只需要在 GROUP_CONCAT() 中使用 DISTINCT

SELECT u.name,
       GROUP_CONCAT(DISTINCT f.name) AS friends
................................................

请注意,SELECT DISTINCT ... 在您的查询中没有意义,因为您使用的是 GROUP BY ,它为每个用户返回不同的行。

查看演示

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage