2013-12-14 62 views
0

,是它在SELECT列表可能重新WHERE子句中的子查詢,像這樣:如何使用相同的子查詢的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 

回答

1

在MySQL中,你可以使用列別名having子句中,而不是where條款。如果你有一個沒有group byhaving子句 - 在MySQL中 - 那麼它的行爲就像是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; 

注意,如果沒有條件,你需要爲同一邏輯left outer join讓那些沒有購買匹配iten。因爲你的條件至少需要兩次這樣的匹配,所以你不需要左連接。

1
SELECT p.id, (SELECT COUNT(*) AS n FROM itens WHERE purchase_id=p.id) AS nItens 
FROM purchase AS p 
HAVING nItens > 1 
+0

是的,我試着問之前,並得到這個錯誤:未知列'nItens'在'where子句' –

+0

之前你問你把'AS nItens'放在Where子句而不是選擇 –

+0

不是,這是爲了解決這個問題。你測試了你的解決方案嗎? –

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 
+0

您是否看過我的問題? –

相關問題