0

请看下表。让我们说第一个是table1另一个table2。我真的不知道该怎么做,谁能帮助我如何用mysql查询计算下表?

用“a”型计算多少“红色”

它计算一个类型有多少红色

谢谢

4

4 回答 4

4

您需要使用,因为有可能在另一个表上LEFT JOIN不存在。INNER JOINcolor

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
于 2013-09-23T15:01:57.710 回答
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
于 2013-09-23T15:04:24.510 回答
0

你可以做一些类似 select count(red) from table1; 我不确定语法,你可以在这里检查

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

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

于 2013-09-23T15:03:35.313 回答
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 计数行

PS 我假设请求的是从 table1 获取 table2 的 MySQL 查询。

于 2013-09-23T15:07:42.910 回答