2011-04-12 35 views
1

使用以下两种(简化)表结构发现我想找到出现在TABLE1所有DISTINCTsession_id值,其中flag = yes请勿出现在TABLE2其中progress = 11MySQL的选择IDS未在其他表在一定条件下

TABLE1没有重复的session_id值。

TABLE1

id_table1 | session_id | flag 
------------------------------ 
1   | abcd  | yes 
2   | efgh  | no 
3   | ijkl  | yes 
4   | mnop  | yes 
5   | vwxyz  | yes 

TABLE2

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 

这里的预期结果是:

abcd 
ijkl 

回答

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) 
+0

它的工作原理,但非常缓慢...有关如何加速它的任何想法? – Jon 2011-04-12 11:45:53

+0

不知道你的索引是什么以及EXPLAIN输出是什么,很难提出任何建议。是根据session_id索引的吗? – 2011-04-12 11:49:20

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

这也可以通过在session_id字段上进行内部连接来完成。 – Andrew 2011-04-12 10:43:11

+0

我认为你不看进步= 11 – Marco 2011-04-12 10:53:53

相关问题