mysql从一个表中选择id,在某些条件下在另一个表中找不到

时间:2011-04-12 10:37:34

标签: mysql join exists

使用以下两个(简化的)表格结构,我希望找到session_idTABLE1所有 DISTINCT flag = yes不要出现在TABLE2 progress = 11

TABLE1

session_id没有重复的id_table1 | session_id | flag ------------------------------ 1 | abcd | yes 2 | efgh | no 3 | ijkl | yes 4 | mnop | yes 5 | vwxyz | yes 值。

TABLE1

id_table2 | session_id | progress
---------------------------------
1         | abcd       | 3
2         | efgh       | 11
3         | ijkl       | 2
4         | ijkl       | 7
5         | mnop       | 11
6         | vwxyz      | 10
7         | vwxyz      | 11

TABLE2

abcd
ijkl

这里的预期结果是:

{{1}}

2 个答案:

答案 0 :(得分:1)

SELECT 

DISTINCT t1.session_id 

FROM
    id_table1 t1 

INNER JOIN 
    id_table2 t2 
ON 
    t1.session_id = t2.session_id 

WHERE
    t1.flag = 'yes'
AND
    t2.progress NOT IN(11)

答案 1 :(得分:0)

select distinct session_id 
from table1 where session_id not in (select session_id from table2) and flag='yes'