Duplication caused by JOIN
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.
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
use group by clause
SELECT users.UserID FROM users
LEFT JOIN bind_groups ON users.UserID = bind_groups.UserID
WHERE groupID = 26 OR groupID = 87
GROUP BY UserID
Use DISTINCT:
SELECT DISTINCT users.UserID FROM users
LEFT JOIN bind_groups ON users.UserID = bind_groups.UserID
WHERE groupID = 26 OR groupID = 87
Try modifying your sql to this:
SELECT DISTINCT users.UserID FROM users
LEFT JOIN bind_groups ON users.UserID = bind_groups.UserID
WHERE groupID = 26 OR groupID = 87
DISTINCT is clear, but depending on the table sizes it can be useful to work with IN
:
SELECT DISTINCT users.UserID FROM users
JOIN bind_groups ON users.UserID = bind_groups.UserID
WHERE groupID IN(26, 87)
精彩评论