Mysql计数选中查询

时间:2013-09-23 14:58:40

标签: mysql select count inner-join

请看下面的表格。让我们说第一个是table1而另一个是table2。 我真的不知道该怎么做,任何人都可以帮我如何计算下面的表格与mysql查询?

计算“a”类型的“红色”数量

its count how much red with a type

感谢

4 个答案:

答案 0 :(得分:4)

您需要使用LEFT JOIN而不是INNER JOIN,因为另一个表格中可能不存在color

SELECT  a.id,
        a.colour,
        SUM(type = 'a') TypeA,
        SUM(type = 'b') TypeB
FROM    tableColors a
        LEFT JOIN tableName b
            ON a.ncolour = b.colour
GROUP   BY a.id, a.colour

SUM(type = 'a')是一种特定于mysql的语法,用于计算布尔运算结果的总值。如果您想要更友好的RDBMS,请使用CASE

SELECT  a.id,
        a.colour,
        SUM(CASE WHEN type = 'a' THEN 1 ELSE 0 END) TypeA,
        SUM(CASE WHEN type = 'b' THEN 1 ELSE 0 END) TypeB
FROM    tableColors a
        LEFT JOIN tableName b
            ON a.ncolour = b.colour
GROUP   BY a.id, a.colour

答案 1 :(得分:1)

SELECT a.colour ncolor,
  SUM(a.type = 'a') amount_a,
  SUM(a.type = 'b') amount_b
  FROM table_name a
  LEFT JOIN table_name b
     ON a.colour = b.colour
  GROUP BY a.id, a.colour

答案 2 :(得分:0)

你可以做一些像table1中的select count(red);我不确定语法,你可以在这里查看

http://dev.mysql.com/doc/refman/5.0/es/counting-rows.html

http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/

答案 3 :(得分:0)

在屏幕上,我会说您要查找的查询很简单SELECT [...], COUNT(a), COUNT(b) FROM table1 GROUP BY colour

更确切地说:

SELECT colour AS ncolour
  , COUNT(a) as amount_a
  , COUNT(b) as amount_b
FROM table1
GROUP BY colour ;

请参阅Mysql Counting Rows

P.S。我假设所请求的是MySQL查询从table1获取table2。