Combine two sql select queries (in postgres) with LIMIT statement

好久不见. 提交于 2020-06-08 03:19:08

问题


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.

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 -

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..


回答1:


Just checked that this will work:

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



回答2:


This will give you records from 10th to 20th and should get you started.i will reply back with 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  


来源:https://stackoverflow.com/questions/13584135/combine-two-sql-select-queries-in-postgres-with-limit-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!