0

我的桌子——

pid     id  subject section
1        1  7            0
2        1  12           0
3        1  13           1
4        1  13           2
5        1  13           3
6        1  14           3
7        1  14           4
8        2  15           1
9        2  16           1

得到的结果——

id subject total
1    7      1
1    12     1
1    13     3
1    14     2

我的查询 -

SELECT DISTINCT(SUBJECT), count(section)
FROM mytable
GROUP BY section
WHERE id = 1

但这是抛出一个错误,让我知道我做错了什么

错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 1' at line 4: SELECT DISTINCT(SUBJECT), count(section) FROM mytable GROUP BY section WHERE id = 1 
4

4 回答 4

2

语法错误是由于放错了WHERE子句。它需要先去 GROUP BY此外:

  • 您正在按要汇总的列进行分组。
  • 您不必要地使用 DISTINCT。

查询应该在这一行:

SELECT SUBJECT, count(section)
FROM mytable
WHERE id = 1
GROUP BY SUBJECT
于 2013-02-21T11:22:36.157 回答
1

您需要这样做,group by subject因为这是独特的价值。在该组中,您要计算 的出现次数section

SELECT 1 as id, subject, count(section) as total
FROM mytable
WHERE id = 1
GROUP BY subject

而且由于该id列不在组中,您可以选择该静态值,也可以将其替换为聚合函数min(id) as id,例如1 as id

于 2013-02-21T11:16:23.843 回答
0

您想按主题而不是按部分分组。而且你不需要不同的——它与 GROUP BY 是多余的。

SELECT id, subject, count(section)
   FROM mytable
   WHERE id = 1
   GROUP BY id, subject
于 2013-02-21T11:16:41.380 回答
0
SELECT SUBJECT, count(section)
FROM mytable
WHERE id = 1
GROUP BY SUBJECT
于 2013-02-21T11:22:56.917 回答