我有以下表格:
industries
-----------
+ id
+ name
users
-----------
+ id
+ name
teams
-----------
+ id
+ name
+ type
user_to_team
-----------
+ id
+ user_id
+ team_id
+ industry_id
我正在运行以下sql查询:
SELECT teams.id
FROM teams
LEFT JOIN user_to_team ON user_to_team.`team_id` = teams.id
WHERE teams.type = 'general'
AND (user_to_team.industry_id NOT IN(1))
GROUP BY user_to_team.team_id
LIMIT 1
问题是它返回user_to_team
表中包含industry_id为1的团队。
答案 0 :(得分:1)
您是否尝试在“ON”子句之后将该条件检查移至该表的“LEFT JOIN”语句中?
SELECT teams.id
FROM teams
LEFT JOIN user_to_team ON user_to_team.`team_id` = teams.id
AND user_to_team.industry_id NOT IN(1)
WHERE teams.type = 'general'
LIMIT 1
此外,您是否拥有该列的正确数据类型?
答案 1 :(得分:0)
这假设任何给定的团队都可以与user_to_team表中的多个行业相关联。
SELECT DISTINCT teams.team_id
FROM teams
LEFT JOIN user_to_team
ON user_to_team.team_id = teams.team_id
AND user_to_team.industry_id = 1
WHERE teams.type = 'general'
AND user_to_team.team_id IS NULL;
答案 2 :(得分:0)
您可以使用LEFT JOIN / IS NULL
SELECT teams.id
FROM teams
LEFT JOIN user_to_team
ON user_to_team.team_id = teams.id
AND user_to_team.industry_id IN (1) -- caution: this is IN
-- and **not** NOT IN
WHERE teams.type = 'general'
AND user_to_team IS NULL ;
或NOT EXISTS
子查询,更易于阅读:
SELECT teams.id
FROM teams
WHERE teams.type = 'general'
AND NOT EXISTS
( SELECT *
FROM user_to_team
WHERE user_to_team.team_id = teams.id
AND user_to_team.industry_id IN (1) -- caution: this is IN
-- and **not** NOT IN
) ;