出于性能目的,是否可以在SELECT列表中重用WHERE子句中的子选择,如:
SELECT p.id, nItens FROM purchase AS p
WHERE ((SELECT COUNT(*) AS n FROM itens WHERE purchase_id=p.id) AS nItens) > 1
避免:
SELECT p.id, (SELECT COUNT(*) AS n FROM itens WHERE purchase_id=p.id) AS nItens
FROM purchase AS p
WHERE (SELECT COUNT(*) AS n FROM itens WHERE purchase_id=p.id) > 1
答案 0 :(得分:1)
SELECT p.id, (SELECT COUNT(*) AS n FROM itens WHERE purchase_id=p.id) AS nItens
FROM purchase AS p
HAVING nItens > 1
答案 1 :(得分:1)
SELECT p.id
, COUNT(n.purchase_id) ttl
FROM purchase p
JOIN itens n
ON n.purchase_id = p.id
GROUP
BY p.id
HAVING ttl > 1
答案 2 :(得分:1)
在MySQL中,您可以在having
子句中使用列别名,但不能在where
子句中使用列别名。如果你在MySQL中有一个没有having
的{{1}}子句 - 那么它的行为就像一个group by
。所以你可以这样做:
where
但是,您的查询可能更好地写为:
SELECT p.id, (SELECT COUNT(*) AS n FROM itens WHERE purchase_id=p.id) AS nItens
FROM purchase AS p
HAVING nItens > 1;
请注意,如果没有条件,您需要一个select p.id, count(*) as nItens
from purchase p join
itens i
on p.id = i.purchase_id
group by p.id
having count(*) > 1;
来获得相同的逻辑,以保持与之无匹配的购买。由于您的条件至少需要两次此类匹配,因此您不需要左连接。