如何按首字母计算行数?

时间:2012-04-14 01:27:58

标签: mysql sql

这是一个菜鸟问题!

我写了这个查询,但是“group by”非常愚蠢...... 那么,我该如何纠正呢?

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

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

提前感谢!

3 个答案:

答案 0 :(得分:13)

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

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%'

答案 1 :(得分: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的索引可确保良好的性能。要了解原因,请查看Anatomy of an SQL Index

答案 2 :(得分:0)

如果你想要它,

应该给你一切

SELECT
  COUNT(*) AS total,
  test
FROM
 (SELECT substring(name,1,1) as test
 from contents) t
GROUP BY test