4

这里有一个菜鸟问题!

我写了这个查询,但是“分组依据”非常愚蠢......那么,我该如何纠正这个问题?

SELECT
    COUNT(*) AS total,
    'x' as test
    FROM
contents
    WHERE name LIKE 'C%'
GROUP BY
    test
ORDER BY id ASC

欢迎使用不同的解决方案和有关表演的信息(也许使用 DISTINCT?)

提前致谢!

4

3 回答 3

15

这应该与任何其他选项一样好 -

SELECT
    LEFT(name, 1) AS first_letter,
    COUNT(*) AS total
FROM contents
GROUP BY first_letter

如果您想一次针对单个字母运行此查询,您可以添加 WHERE 子句并删除 GROUP BY -

SELECT COUNT(*) AS total
FROM contents
WHERE name LIKE 'a%'
于 2012-04-14T01:33:00.743 回答
1

让我们剖析您的查询:

SELECT
    COUNT(*) AS total,
    'x' as test     <-- Why?
    FROM            <-- Bad formatting.
contents
    WHERE name LIKE 'C%'
GROUP BY
    test            <-- Removing 'x' and the whole GROUP BY has the same effect.
ORDER BY id ASC     <-- The result only contains one row - nothing to sort.

因此,返回一行和一个字段的查询,包含name以“C”开头的行数,如下所示:

SELECT COUNT(*)
FROM contents
WHERE name LIKE 'C%'

拥有领先优势的索引name将确保良好的性能。要了解原因,请查看SQL 索引剖析

于 2012-04-14T01:42:58.230 回答
0

应该给你一切,以备不时之需

SELECT
  COUNT(*) AS total,
  test
FROM
 (SELECT substring(name,1,1) as test
 from contents) t
GROUP BY test
于 2012-04-14T01:33:07.823 回答