how to count rows by first letter?

前端 未结 3 544
暗喜
暗喜 2021-01-14 17:21

a noob question here!

I wrote this query, but the \"group by\" is very stupid... so, how can I correct this?

SELECT
    COUNT(*) AS total,
    \'x\'         


        
3条回答
  •  庸人自扰
    2021-01-14 17:57

    Let's dissect your query:

    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.
    

    So the query that returns one row with one field, containing the number of rows whose name begins with 'C' would look like this:

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

    Having an index whose leading edge is name would ensure good performance. To understand why, take a look at the Anatomy of an SQL Index.

提交回复
热议问题