我有两张桌子:
表1:
users
========+===========
user_id | user_name
--------+-----------
1 | bn
2 | gn
3 | en
表2:
user_attr
========+===========+=============
user_id | attr_name | attr_value
--------+-----------+-------------
1 | sell | 1
2 | first | 245
1 | au | 246
2 | sell | 1
在PostgreSQL中,我想要来自'au'
表中没有'first'
,'sell'
或user_attr
的表用户的用户ID。
我测试了下面的查询但没有工作:
SELECT users.user_id
FROM users
INNER JOIN user_attrs ON users.user_id = user_attrs.user_id
WHERE
users.group_id = '$group' AND (user_attrs.attr_name != 'first'
AND user_attrs.attr_name != 'sell' AND user_attrs.attr_name != 'au')
LIMIT 1;
答案 0 :(得分:1)
我遇到了什么问题。如果数据与你给我们的相同,那就很简单了,你使用内连接和attrs表只得到user_id = 1和2.所以你什么都没有。试试左连接:
SELECT users.user_id FROM users
LEFT JOIN user_attrs ON users.user_id = user_attrs.user_id
WHERE users.group_id = '$group'
AND (user_attrs.attr_name != 'first'
AND user_attrs.attr_name != 'sell'
AND user_attrs.attr_name != 'au')
LIMIT 1
答案 1 :(得分:0)
SELECT users.user_id
FROM users
INNER JOIN user_attrs ON users.user_id = user_attrs.user_id
WHERE users.group_id = '$group'
AND user_attrs.attr_name NOT IN ('first','au','sell') LIMIT 1";