MySQL单个查询以填充字母词汇表

时间:2020-12-22 00:09:18

Experts, I'm creating a glossary that has each letter of the alphabet as a link at the top - users can select a particular letter to see results that start with that letter. For example:

专家,我正在创建一个词汇表,其中每个字母都作为顶部链接 - 用户可以选择一个特定的字母来查看以该字母开头的结果。例如:

[All] [A] [B] [C] [D] ... [X] [Y] [Z]

But I don't have results for every letter so I don't want those letters to be clickable. So if there are no results that start with "X" for example, I would display [X] without a hyperlink. Otherwise, users have to click on a letter to see if there are results or not, which could be annoying.

但是我没有每个字母的结果,所以我不希望这些字母是可点击的。因此,如果没有以“X”开头的结果,我会显示没有超链接的[X]。否则,用户必须单击一个字母以查看是否有结果,这可能很烦人。

My question is: Is there a single mysql query that can tell me how many results for a particular column (say "Name") that start with each letter of the alphabet? I'm trying to avoid executing a query for each letter as I'm rendering the page...

我的问题是:是否有一个mysql查询可以告诉我从字母表的每个字母开始的特定列(比如“名称”)有多少结果?我正在尝试避免为每个字母执行查询,因为我正在渲染页面...

I'm looking for a something like:

我正在寻找类似的东西:

NameThatStartsWith   NumOfResults
        A                 23
        B                 11
        C                 32 
       etc...
        X                  0

1 个解决方案

#1


3  

SELECT LEFT(Name, 1) as NameThatStartsWith, COUNT(*) as NumOfResults
FROM your_table GROUP BY LEFT(Name, 1)

#1


3  

SELECT LEFT(Name, 1) as NameThatStartsWith, COUNT(*) as NumOfResults
FROM your_table GROUP BY LEFT(Name, 1)