postgresql 将两个 sql 选择查询(在 postgres 中)与 LIMIT 语句结合起来
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13584135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Combine two sql select queries (in postgres) with LIMIT statement
提问by Aidan Ewen
I've got a table and I want a query that returns the last 10 records created plus the record who's id is x.
我有一个表,我想要一个查询,该查询返回创建的最后 10 条记录以及 ID 为 x 的记录。
I'm trying to do -
我正在尝试做 -
SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10
UNION
SELECT * FROM catalog_productimage
WHERE id=5;
But it doesn't look like I can put LIMIT
in there before UNION
. I've tried adding another column and using it for sorting -
但看起来我LIMIT
之前不能放在那里UNION
。我尝试添加另一列并使用它进行排序 -
SELECT id, date_modified, IF(false, 1, 0) as priority FROM catalog_productimage
UNION
SELECT, id, date_modified, IF(true, 1, 0) as priority FROM catalog_productimage
WHERE id=5
ORDER BY priority, date_modified
LIMIT 10;
but I'm not making much progress..
但我没有取得太大进展..
回答by sufleR
Just checked that this will work:
刚刚检查这是否有效:
(SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10)
UNION
SELECT * FROM catalog_productimage
WHERE id=5;
回答by sayannayas
This will give you records from 10th to 20th and should get you started.i will reply back with SQLfiddle
这会给你从 10 日到 20 日的记录,应该让你开始。我会用 SQLfiddle 回复
SELECT *
FROM (SELECT ROW_NUMBER () OVER (ORDER BY cat_id) cat_row_no, a.* FROM catalog_productimage a where x=5)
WHERE cat_row_no > 10 and cat_row_no <20