0

为简单起见,假设您有两张桌子...

users:
  user_id
  name
  age

clothing:
  user_id
  type
  color

您将如何选择所有 21 岁且根本没有任何衬衫或有衬衫但没有任何红色衬衫的用户?到目前为止,我的尝试看起来像......

SELECT users.user_id
FROM users LEFT JOIN clothing
ON users.user_id = clothing.user_id
AND clothing.type = shirt
AND clothing.color != red
WHERE users.age = 21;

如果我只想选择表中没有条目的用户的条目clothingWHERE clothing.user_id IS NULL

4

2 回答 2

2
SELECT users.user_id FROM users
WHERE users.age = 21
AND users.user_id NOT IN
    (SELECT user_id FROM clothing WHERE user_id IS NOT NULL AND type = 'shirt' AND color = 'red')

实际上更简单的方法是找出所有穿红衬衫的人,然后说,“把所有不在那个组的人都给我。” 话虽这么说,我认为你实际上需要clothing分成两张表:一张只列出衣服,另一张链接user_idclothing_id.

于 2013-11-01T20:34:25.510 回答
0

怎么样:

SELECT users.user_id
FROM users u1 LEFT OUTER JOIN clothing c  # outer join makes sure you get a user back.
ON users.user_id = c.user_id
where c.type = shirt AND
(count(select * from users u2 where u1.user_id =- u2.user_id LEFT INNER JOIN clothing c2 on u2.user_id = c2.user_id) > 0 OR 
c.color != red) AND
users.age = 21;
于 2013-11-01T20:31:08.650 回答