MySQL - WHERE每个值都是IN

时间:2012-08-14 21:22:13

标签: mysql

以下查询选择输入为“完成”的所有工作(第7行的子查询)。当只有一个输入时,这工作正常。我如何更改它,以便它需要每个输入都是子查询返回的集合,而不仅仅是要出现的输入之一?

SELECT workunits.ID 
FROM workunits 
LEFT JOIN workunitInputs ON workunits.ID = workunitInputs.workunitID 
WHERE workunits.ID NOT IN (SELECT workunitID FROM jobworkunitassoc) 
AND ( 
    workunitInputs.inputID IN ( 
        SELECT workunitOutputs.outputID 
        FROM workunitOutputs 
        LEFT JOIN workunits ON workunitOutputs.workunitID = workunits.ID 
        LEFT JOIN jobworkunitassoc ON workunits.ID = jobworkunitassoc.workunitID 
        LEFT JOIN jobs ON jobworkunitassoc.jobID = jobs.ID 
        WHERE jobs.done = 1 
    ) 
    OR workunitInputs.inputID IS NULL 
) 
GROUP BY workunits.ID

谢谢,Istvan。

2 个答案:

答案 0 :(得分:0)

将该条款更改为:

AND ( 
    workunitInputs.inputID NOT IN ( 
        SELECT workunitOutputs.outputID 
        FROM workunitOutputs 
        LEFT JOIN workunits ON workunitOutputs.workunitID = workunits.ID 
        LEFT JOIN jobworkunitassoc ON workunits.ID = jobworkunitassoc.workunitID 
        LEFT JOIN jobs ON jobworkunitassoc.jobID = jobs.ID 
        WHERE jobs.done != 1 
    )

这是基于逻辑重言式:Y中的所有X = Y中没有X!Y

答案 1 :(得分:0)

此查询适用于我,但它可能不是最佳解决方案: http://pastebin.com/g9qBjQGU