使用LIMIT语句组合两个sql select查询(在postgres中)

时间:2012-11-27 12:20:23

标签: sql postgresql select limit union

我有一个表,我想要一个查询,返回创建的最后10条记录加上id为x的记录。

我正在尝试 -

SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10
UNION
SELECT * FROM catalog_productimage
WHERE id=5;

但在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;

但我没有取得多大进展..

2 个答案:

答案 0 :(得分:46)

刚检查一下这是否有效:

(SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10)
UNION
SELECT * FROM catalog_productimage
WHERE id=5;

答案 1 :(得分:1)

这将为您提供从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