2

I need the amount of words that start from all the characters of the alphabet, exist in my database

I tried the following query:

SELECT 
    COUNT(id) FROM(SELECT id FROM words WHERE word LIKE 'A%') as A,
    COUNT(id) FROM(SELECT id FROM words WHERE word LIKE 'B%') AS B,
    ...
    COUNT(id) FROM(SELECT id FROM words WHERE word LIKE 'Z%') AS Z

When I run the query, it gives me this error:

Incorrect syntax near 'COUNT'.    
Incorrect syntax near the keyword 'AS'.

The funny thing is that the query works fine if I only ask for the words that start with 'A'

What am I doing wrong?

EDIT

Just to clarify for future readers. The reason I want one check per letter of the alphabet, is because the alphabet can be different according to the language of the user and is going to be provided each time the query is generated

4

4 に答える 4

1

最初の文字をサブストリング化することをお勧めします。

select
substring(word,1,1) as firstChar,
count(id)
from...
group by
substring(word,1,1) 

これは、26 個の個別のチェックよりも簡単に思えます。

于 2013-10-30T16:38:04.730 に答える
1

結果を列ではなく行に表示してもかまわない場合は、次のようにします。

SELECT LEFT(word, 1) aChar, count(id) total
FROM words
WHERE word LIKE '[A-Z]%'
GROUP BY LEFT(word, 1)

ここでフィドル。

また、あなたのコメントによると:

ユーザーの言語によってアルファベットが異なるため、これらすべてのチェックを行う必要があります。

正規表現の値をパラメータ化し、クエリのコード (パラメータのみ) を変更せずに文字を追加または削除できるため、ここで正規表現を使用する方がはるかに理にかなっています。

于 2013-10-30T17:09:02.380 に答える
0

操作をサブクエリから分離する必要はありませんCOUNT。インラインで実行できます。

SELECT
    (SELECT COUNT(*) FROM words WHERE word LIKE 'A%') AS A,
    (SELECT COUNT(*) FROM words WHERE word LIKE '%B') AS B,
    (SELECT COUNT(*) FROM words WHERE word LIKE '%C') AS C
于 2013-10-30T16:32:17.523 に答える