此查询有效:
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
)?
答案 0 :(得分: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 :(得分:3)
<{1}}和select
之后 from
中的内容被评估(最好的回忆一下,where
和{{1}或者至少直到Postgres的最新版本。)
您还需要在where子句中输入完整的子查询,因为在引用该列时未定义该列:
group by
你也可以使用having
/ 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
上进行索引,您就可以在其上添加索引并使用OR位图索引扫描来获取行。