涉及多列的子查询

时间:2013-02-11 11:31:56

标签: mysql

我想要一个查询来返回另一个表中不存在的值。我目前运行两个查询并在代码中执行交集。在where

之后,我坚持使用多列的语法和语句的存在

首先查询:

SELECT sid, cid 
FROM  Table2
where used = 0
group by sid, cid

主要查询:

SELECT    sid, cid, count(1) as cnt 
FROM      Table1
WHERE     ##not any pair of (sid, cid) returned from first query##
GROUP BY  sid, cid 
HAVING    cnt < 20 
LIMIT     50

什么是完整的主要查询?

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT    t1.sid, t1.cid, count(1) as cnt 
FROM      Table1 t1
LEFT JOIN Table2 t2
ON        t1.sid = t2.sid AND t1.cid = t2.cid AND t2.used = 0
WHERE     t2.sid IS NULL AND t2.cid IS NULL
GROUP BY  sid, cid 
HAVING    cnt < 20 
LIMIT     50