简体   繁体   English

计数在mysql上的每一行

[英]Count for each row on mysql

i have this query: 我有这个查询:

SELECT 
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 4) AS desejo,
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 2) AS europa,
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 6) AS futebol,
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 8) AS jazz,
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 3) AS praia,
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 1) AS sp,
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 7) AS tamta,
    (SELECT COUNT(*) FROM tb_pinturas WHERE c.catId= 5) AS velocidade,
    c.catNome AS nome, 
    c.catSlug AS slug, 
    c.catId AS id  
FROM aux_categoria c 
LEFT JOIN tb_pinturas p ON(c.catId = p.catId)
GROUP BY c.catid    ORDER BY c.catNome;

and i want to make just one column for each count. 我想为每个计数只写一列。 What should i do? 我该怎么办?

Something like this should work for you: 这样的事情应该为您工作:

SELECT 
    c.catNome AS nome, 
    c.catId AS id,
    count(p.catId) as the_count  
FROM aux_categoria c 
LEFT JOIN tb_pinturas p ON(c.catId = p.catId)
GROUP BY c.catNome,c.catid    
ORDER BY c.catNome

You don't need each subquery. 您不需要每个子查询。 You can use SUM() to count the values return by the boolean expression. 您可以使用SUM()来计算布尔表达式返回的值。

SELECT  SUM(c.catId = 4) AS desejo,
        SUM(c.catId = 2) AS europa,
        SUM(c.catId = 6) AS futebol,
        SUM(c.catId = 8) AS jazz,
        SUM(c.catId = 3) AS praia,
        SUM(c.catId = 1) AS sp,
        SUM(c.catId = 7) AS tamta,
        SUM(c.catId = 5) AS velocidade,
        c.catNome AS nome, 
        c.catSlug AS slug, 
        c.catId AS id  
FROM    aux_categoria c 
        LEFT JOIN tb_pinturas p 
            ON c.catId = p.catId
GROUP   BY  c.catid,
            c.catNome, 
            c.catSlu  
ORDER   BY  c.catNome

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM