我有以下postgres查询,该查询可为我提供所需的结果,但由于运行两次相同的内部查询,我觉得它没有经过优化。我尝试了一个分组依据,但一直说我必须将xdata.column_name添加到分组依据。我必须获取total_count
,因为我正在使用这些结果创建分页。任何帮助将不胜感激。
SELECT total.total_count, xdata.* FROM (SELECT * FROM (SELECT *, CAST(celery_taskresult.meta -> 'args' ->> 0 AS INT) AS user_id, celery_taskresult.meta ->> 'name' AS task_name FROM celery_taskresult) AS x
WHERE x.user_id IS NOT NULL) as xdata
LEFT JOIN (SELECT COUNT(z.id) AS total_count, 0 AS b FROM (SELECT *, CAST(celery_taskresult.meta -> 'args' ->> 0 AS INT) AS user_id, celery_taskresult.meta ->> 'name' AS task_name FROM celery_taskresult) AS z
WHERE z.user_id IS NOT NULL) as total ON 0 = total.b
ORDER BY xdata.id ASC
LIMIT 25 OFFSET 0
答案 0 :(得分:1)
我已经有一段时间没有使用postgresql了,但是选择COUNT(*) OVER()
应该可以
SELECT COUNT(*) OVER() AS total_count,
xdata.*
FROM (SELECT *
FROM (SELECT *,
CAST(celery_taskresult.meta -> 'args' ->> 0 AS INT) AS user_id,
celery_taskresult.meta ->> 'name' AS task_name
FROM celery_taskresult) AS X
WHERE x.user_id IS NOT NULL) AS xdata
ORDER BY xdata.id ASC
LIMIT 25 OFFSET 0
编辑:PostgreSQL窗口上的文档窗口功能-Window Functions
答案 1 :(得分:0)
您可以使用cte。
https://www.tutorialspoint.com/postgresql/postgresql_with_clause.htm。
例如
使用cte作为(从a中选择*),从cte中选择*;
将内部的select *替换为select *,并使用它。