Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplication caused by JOIN

Tags:

sql

mysql

I created a simple query which contains a JOIN, and this JOIN 'makes' some duplications.

Table users:

UserID  Name
------  ----
1       Luis
2       Andre
3       Mark
4       Linda

Table bind_groups:

groupID UserID
------- ------
26      1
87      2
87      1
12      4
41      4
6       1
21      2
5       3

The SQL query:

SELECT users.UserID FROM users
    LEFT JOIN bind_groups ON users.UserID = bind_groups.UserID
    WHERE groupID = 26 OR groupID = 87

The result will be:

UserID
------
1
2
1

As you can see, it returns the UserID = 1 twice (because it appears twice, in groupID 26 and groupID 87).

What should I do if I want to return it one time and not the number of the times it appears in the groups?

Thank you.

like image 689
Luis Avatar asked May 25 '26 04:05

Luis


1 Answers

select distinct users.UserID from users ...

There is no need for it to be a left join either, your where clause makes it an inner join

like image 87
Andrew Avatar answered May 27 '26 16:05

Andrew