开发者

PSQL request too slow. How to fix it?

开发者 https://www.devze.com 2023-03-20 05:49 出处:网络
SELECT COUNT(a)/COUNT(s)*100 as aratio, COUNT(b)/COUNT(s)*100 as bratio, COUNT(c)/COUNT(s)*100 as cratio,
SELECT 
    COUNT(a)/COUNT(s)*100 as aratio, 
    COUNT(b)/COUNT(s)*100 as bratio, 
    COUNT(c)/COUNT(s)*100 as cratio, 
    COUNT(a), 
    COUNT(b), 
    COUNT(c), 
    COUNT(s) 
FROM 
    (SELECT COUNT(cid) as a FROM images WHERE width > height AND category_id = 4 GROUP BY cid) as aq, 
    (SELECT COUNT(cid) as b FROM images WHERE width < height AND category_id = 4 GROUP BY cid) as bq, 
    (SELECT COUNT(cid) as c FROM images WHERE width = height AND category_id = 4 GROUP BY cid) as cq, 
    (SELECT COUNT(cid) as s FROM images WHERE category_id = 4 GROUP BY cid) as sq;

How can i开发者_开发问答 make this request more effective?


it is possible with using WITH. Move all queries to WITH and modify them a little: change COUNT(cid) to COUNT(DISTINCT cid) and remove GROUP BY clause at all.


You could use something like this:

SELECT 
    SUM(CASE (width > height) WHEN true THEN 1 ELSE 0 END)::float8*100/COUNT(*) as aratio, 
    SUM(CASE (width < height) WHEN true THEN 1 ELSE 0 END)::float8*100/COUNT(*) as bratio, 
    SUM(CASE (width = height) WHEN true THEN 1 ELSE 0 END)::float8*100/COUNT(*) as cratio, 
    SUM(CASE (width > height) WHEN true THEN 1 ELSE 0 END), 
    SUM(CASE (width < height) WHEN true THEN 1 ELSE 0 END), 
    SUM(CASE (width = height) WHEN true THEN 1 ELSE 0 END), 
    COUNT(*) 
FROM 
    images WHERE category_id = 4;

this query doesn't grouping by cid, but probably you don't need it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号