从另一个查询中使用resolute从表中选择

时间:2012-07-24 18:45:14

标签: mysql

你看,t1和t2有一些类似的行,在第一个查询中我选择了那些不匹配的行,我使用了以下查询

SELECT DISTINCT t1.usr_id
FROM t1, t2
WHERE t1.usr_id != t2.usr_id
AND t1.event =  '$event'
AND t1.client =  '$client'
GROUP BY t1.usr_id

现在我想使用上面查询的结果从t3中选择*匹配usr_id。 我尝试了其他几乎相似的问题的答案,但没有一个是从一个查询中减去并使用结果从第二个查询中获取数据

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT t3.usr_id FROM t3 WHERE t3.usr_id IN 
(SELECT DISTINCT t1.usr_id
FROM t1, t2
WHERE t1.usr_id != t2.usr_id
AND t1.event =  '$event'
AND t1.client =  '$client'
GROUP BY t1.usr_id)

但它可能比以下慢:

SELECT table.usr_id
FROM ( SELECT DISTINCT t1.usr_id
FROM t1, t2
WHERE t1.usr_id != t2.usr_id
AND t1.event =  '$event'
AND t1.client =  '$client'
GROUP BY t1.usr_id ) as table
JOIN t3 ON t3.usr_id = table.usr_id