2013-12-18 77 views
0

每一行,我有此查詢:計數關於MySQL

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; 

,我想爲每個計數剛一列。我該怎麼辦?

+1

不知道你問這裏有什麼..你似乎每一列了。 –

+0

我想帶名字,id和count列,只有3列 –

回答

1

像這樣的東西應該爲你工作:

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 
+0

@Ike Walker! –

0

你不需要每個子查詢。您可以使用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

那就是它,但是如何查詢catNome的一個列組? –