Home  >  Q&A  >  body text

Mysql DISTINCT still returns duplicate values

How to avoid duplicates on friends, I still get two bob instead of just one bob

My table setup:

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

The query I used:

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;

Current results:

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

My expectations:

name    friends
Matt    Lance,Bob
Tim Lance,Bob

P粉369196603P粉369196603241 days ago333

reply all(2)I'll reply

  • P粉706038741

    P粉7060387412024-02-22 00:49:54

    Your u.name is different from f.name

    Try this

    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;

    reply
    0
  • P粉714844743

    P粉7148447432024-02-22 00:23:39

    You just need to use DISTINCT in GROUP_CONCAT():

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

    Please note that SELECT DISTINCT ... does not make sense in your query because you are using GROUP BY which returns different rows for each user.

    ViewDemo.

    reply
    0
  • Cancelreply