我不知道为什么此SQL不返回任何行:
SELECT team_rel.team_id
, team_rel.login_id
FROM team_rel
INNER JOIN team ON team_rel.login_id = team.login_id
WHERE team.login_id = '39'
AND NOT EXISTS (
SELECT 0
FROM team_rel
INNER JOIN team ON team_rel.login_id = team.login_id
AND team_rel.login_id = '39'
AND team_rel.team_id = team.id
)
同时执行以下SQL(相同,但没有NOT EXISTS条件):
SELECT team_rel.team_id
, team_rel.login_id
FROM team_rel
INNER JOIN team ON team_rel.login_id = team.login_id
WHERE team.login_id = '39'
返回:
+---------+----------+
| team_id | login_id |
+---------+----------+
| 23 | 39 |
+---------+----------+
| 23 | 39 |
+---------+----------+
| 13 | 39 |
+---------+----------+
| 13 | 39 |
+---------+----------+
| 16 | 39 |
+---------+----------+
| 16 | 39 |
+---------+----------+
| 25 | 39 |
+---------+----------+
| 25 | 39 |
+---------+----------+
和NOT EXISTS子查询(与SQL相同的SQL,对team_id进行测试)返回:
SELECT team_rel.team_id
, team_rel.login_id
FROM team_rel
INNER JOIN team ON team_rel.login_id = team.login_id
AND team_rel.login_id = '39'
AND team_rel.team_id = team.id
返回:
+---------+----------+
| team_id | login_id |
+---------+----------+
| 23 | 39 |
+---------+----------+
| 25 | 39 |
+---------+----------+
我希望我的第一个选择返回:
+---------+----------+
| team_id | login_id |
+---------+----------+
| 13 | 39 |
+---------+----------+
| 16 | 39 |
+---------+----------+
但是它不返回任何行吗?!
答案 0 :(得分:1)
SELECT DISTINCT team_rel.team_id, team_rel.login_id
FROM team_rel
INNER JOIN team ON team_rel.login_id = team.login_id
WHERE team_rel.login_id = 39
AND team_rel.team_id NOT IN
(SELECT team_id FROM team_rel
INNER JOIN team ON team.id = team_rel.team_id AND
team.login_id = team_rel.login_id)