sql连接与where和1-n连接

时间:2013-03-21 15:12:42

标签: mysql sql

我们有两张桌子:

UserTable

userid   username
1        test
2        test2
3        test3


UserStatus

statusid userid status
1        1      1
2        1      3
3        1      7
4        2      1

现在我们需要一个用户列表,其中的用户具有状态3。

有任何想法吗?

4 个答案:

答案 0 :(得分:3)

您可以使用NOT EXISTS

select u.userid,
  u.username
from usertable u
where not exists (select s.userid
                  from userstatus s
                  where s.status = 3
                    and u.userid = s.userid);

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

您可以使用NOT IN:

SELECT usertable.*
FROM usertable
WHERE userid NOT IN (SELECT userid from userstatus where status=3)

请参阅小提琴here

答案 2 :(得分:1)

SELECT username from UserTable
WHERE userid NOT IN (SELECT userid FROM UserStatus WHERE status = 3)

答案 3 :(得分:1)

SELECT * FROM UserTable
WHERE userid NOT IN
(SELECT userid FROM UserStatus WHERE status = 3)