所以我有这个我必须在SQL中做的事情,我不知道为什么逻辑在逃避我。
假设我有一个已经存在且有效的查询:
SET someValue = 1 --let's say someValue is 0 before this query
WHERE EXISTS (SELECT 1 FROM a_tbl WHERE valueA = a_tbl.id)
AND NOT EXISTS (SELECT 1 FROM b_tbl WHERE valueB = b_tbl.id)
现在我想添加另一个存在语句,如果
SELECT 1 FROM b_tbl WHERE valueB = b_tbl.id
返回一行(也就是真的),然后另一个SELECT语句也必须返回一行,如:
SELECT 1 from c_tbl WHERE valueC = c_tbl.id
因此,如果值B<>,则将someValue设置为1 b_tbl.id或valueC<> c_tbl.id
这是我的第一个猜测:
SET someValue = 1 --let's say someValue is 0 before this query
WHERE EXISTS (SELECT 1 FROM a_tbl WHERE valueA = a_tbl.id)
AND (NOT EXISTS (SELECT 1 FROM b_tbl WHERE valueB = b_tbl.id)
AND NOT EXISTS (SELECT 1 from c_tbl WHERE valueC = c_tbl.id))
但是当valueB<>时,这似乎不起作用b_tbl.id(即someValue不应该设置为1)
希望这是有道理的,我知道我可能没解释得很好。
答案 0 :(得分:1)
简单布尔代数。您当前的查询是:
valueA = a_tble.id and valueB <> b_tble.id
并且,如果我正确地阅读您的要求,您希望它是这样的:
valueA = a_tble.id and (valueB <> b_tble.id or valueC <> c_tble.id)
转换为:
WHERE EXISTS (SELECT 1 FROM a_tbl WHERE valueA = a_tbl.id)
AND (NOT EXISTS (SELECT 1 FROM b_tbl WHERE valueB = b_tbl.id)
OR NOT EXISTS (SELECT 1 from c_tbl WHERE valueC = c_tbl.id))