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\'
This should perform as well as any other option -
SELECT
LEFT(name, 1) AS first_letter,
COUNT(*) AS total
FROM contents
GROUP BY first_letter
If you want to run this query for a single letter at a time you can add the WHERE clause and drop the GROUP BY -
SELECT COUNT(*) AS total
FROM contents
WHERE name LIKE 'a%'
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.
should give you everything in case you want it
SELECT
COUNT(*) AS total,
test
FROM
(SELECT substring(name,1,1) as test
from contents) t
GROUP BY test