У меня есть этот запрос:

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;

И я хочу сделать только один столбец для каждого подсчета. Что я должен делать?

0
Thiago Masano Cavaloti 18 Дек 2013 в 20:13

2 ответа

Лучший ответ

Что-то вроде этого должно сработать для вас:

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
1
Ike Walker 18 Дек 2013 в 16:30

Вам не нужен каждый подзапрос. Вы можете использовать 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
0
John Woo 18 Дек 2013 в 16:17