【发布时间】:2013-07-18 21:47:38
【问题描述】:
我卡在 SQL 子查询选择上。现在,我有一个表产品:
id | name | description
----+-------+----------------------
6 | 123 | this is a +
| | girl.
7 | 124 | this is a +
| | girl.
8 | 125 | this is a +
| | girl.
9 | 126 | this is a +
| | girl.
10 | 127 | this is a +
| | girl.
11 | 127 | this is a +
| | girl. Isn't this?
12 | 345 | this is a cute slair
13 | ggg | this is a +
| | girl
14 | shout | this is a monster
15 | haha | they are cute
16 | 123 | this is cute
我要做的是找到(记录总数和前5条记录 ) 在 name 或 description 列中包含 '1' 或 'this'。
我能想到的太丑了:
SELECT *, (select count(id)
from (SELECT * from products
where description like any (array['%1%','%this%'])
or name like any (array['%1%','%this%'])
) as foo
) as total
from (SELECT * from products
where description like any (array['%1%','%this%'])
or name like any (array['%1%','%this%']))
) as fooo
limit 5;
【问题讨论】:
-
为什么不运行 2 个单独的查询?
-
@Yuriy 谢谢,你能给我举个例子吗?
-
simple 运行第一个仅返回 count 且没有任何 WHERE 条件或 LIMIT 限制的查询;第二个查询返回所有列,但将它们限制为 5 条记录并使用您的 WHERE 条件
-
@YuriyGalanter 感谢您的回复。我想过,但实际上有100000多条记录,我问了这个问题,有人说我不应该把它们都归还,因为要统计它们
-
您想要qualifying 记录的总数还是表中的记录总数?我假设是前者,这意味着@Yuiy 的评论需要include
WHERE子句。否则,这是一个有效的解决方案,它不返回所有记录,只返回计数。
标签: sql postgresql count pattern-matching window-functions