2014-01-16 67 views
3

此查詢的工作:過濾上的值使用子查詢計算

select r.id, name, description, private, auth, 
(select count (*) from message m where m.room = r.id) as messageCount 
from room r left join room_auth a on a.room=r.id and a.player='11' 
where private is false or auth is not null; 

這一個不:

select r.id, name, description, private, auth, 
(select count (*) from message m where m.room = r.id) as messageCount 
from room r left join room_auth a on a.room=r.id and a.player='11' 
where private is false or auth is not null or messageCount>1000; 

我得到這個錯誤:

ERREUR: the « messageCount » column doesn't exit 

我怎樣才能乾淨有效地添加條件messageCount?或者更一般地說,如何達到預期的結果(由於room表和聯接中的列數,對於直接查詢message表和room的組的查詢,我沒有真正的興趣)?

回答

3

移動子查詢的WHERE子句:

select sometable.id from sometable 
where id in (select id from someothertable) 

例小提琴:

http://sqlfiddle.com/#!12/02c79/1

適用於您的查詢:

select 
    r.id, 
    name, 
    description, 
    private, 
    auth, 
    (select count (*) from message m where m.room = r.id) as messageCount 
from room r 
    left join room_auth a on a.room = r.id and a.player = '11' 
where 
    private is false or 
    auth is not null or 
    (select count (*) from message m where m.room = r.id) > 1000; 

(免責聲明 - 不知道這將工作完美,因爲我是一個MSSQL的人,所以可能會有一些索姆在Postgreë警告)

+1

工作,+1,但...這是如此醜陋... –

3

select的東西是評估的Postgres fromwhere(和,最好的我記得,group byhaving,或至少做了,直到最近的版本)之後。

您需要在where子句中輸入完整的子查詢過,因爲該列是不確定的,當你引用它:

select r.id, name, description, private, auth, 
(select count (*) from message m where m.room = r.id) as messageCount 
from room r left join room_auth a on a.room=r.id and a.player='11' 
where private is false or auth is not null 
    or (select count (*) from message m where m.room = r.id)>1000; 

你也可以使用一個join/group by/having條款做相同的,同時避免相關的子查詢,因爲後者將表現非常糟糕。

最後,你可以 - 而且實際上應該 - 用你的房間保持你房間的計數。一個觸發器。這樣,如果您的索引號爲privateauth,則可以在其上放置索引並使用「或」位圖索引掃描來提取您的行。

+0

太糟糕了,你是5分鐘遲到;) –

+0

雅,我看到了,但我確實增加了更多信息。 ;-) –

+0

是的,這就是爲什麼你有+1 –