我有这个查询,其中MINUS
运算符的两个操作数被计算两次。
如何重写查询以便只创建一次?
(目的是检查两组是否相等)
SELECT DISTINCT t1.id
FROM t1
WHERE NOT EXISTS (SELECT t2.did FROM t1 AS t2
WHERE t2.id = t1.id
MINUS
SELECT t3.did FROM t3
WHERE t3.price > 500000)
AND NOT EXISTS (SELECT t3.did FROM t3
WHERE t3.price > 500000
MINUS
SELECT t2.did FROM t1 AS t2
WHERE t2.id = t1.id);
为了澄清事情,以下两个[sub]查询在查询中重复两次:
SELECT t2.did FROM t1 AS t2
WHERE t2.id = t1.id
和
SELECT t3.did FROM t3
WHERE t3.price > 500000
答案 0 :(得分:2)
with
ALL_DID as (
select did from t3
where price > 500000
),
PAIRS as (
select
id, t3.did
from t1
left join ALL_DID t3
on t1.did = t3.did
)
select id from PAIRS
group by id
having count(did) = (
select count(0) from ALL_DID
)
minus
select id from PAIRS
where did is null
答案 1 :(得分:0)
如果您只想重复使用同一个查询,请查看使用公用表表达式。或者您可以查看创建视图。这些方法可以快速“重用”相同的查询。
但是,我仍然不完全明白你想要的结果是什么。您是否想知道t1中的数据是否与t3中的数据相同,基于did / eid字段?如果是这种情况,似乎你可以使用LEFT JOIN来更轻松地解决这个问题。像这样:
SELECT DISTINCT t1.id
FROM t1
LEFT JOIN t3 ON t1.did = t3.did AND t3.price > 500000
WHERE t3.id IS NULL
这将告诉您t1中是否有任何不在t3中的记录(具有相同的do和价格> 500000)。
编辑 - 要查找销售价格超过500000的所有产品的所有人的ID,这应该有效:
SELECT t1.id, COUNT(DISTINCT t1.did) productcnt
FROM t1
JOIN t3 ON t1.did = t3.did
WHERE t3.Price > 500000
GROUP BY t1.id
HAVING COUNT(DISTINCT t1.did) = (
SELECT COUNT(DISTINCT did) cnt
FROM t3
WHERE Price > 500000 )
答案 2 :(得分:-1)
这不是正常的内连接查询吗?
SELECT t2.*
from t1
INNER JOIN t3 as t3 on t1.did = t3.tid
INNER JOIN t1 as t2 on t2.did = t1.id
WHERE t3.price > 50000