Jump to content

Archived

This topic is now archived and is closed to further replies.

ctn8iv

Alphabetical Index using GROUP BY

Recommended Posts

I have a MySQL table that contains hundreds of store names, so I want to create an alphabetical listing grouped by letter. However, using the SQL and PHP below, I can only get the first record for each letter. What am I missing?

SELECT *, substring(store,1,1) AS first_letter, count(*) AS store_cnt FROM stores GROUP BY first_letter ORDER BY store;

<?php
$row = 0;
while ($item = mysql_fetch_array($qry_stores)) {
$row = $row + 1;
echo $item['store']; ?><br />
<?php
} ?>

Share this post


Link to post
Share on other sites
[!--sql--][div class=\'sqltop\']SQL[/div][div class=\'sqlmain\'][!--sql1--][span style=\'color:blue;font-weight:bold\']SELECT[/span] *, substring(store,1,1) [color=green]AS[/color] first_letter, [color=blue]count[/color](*) [color=green]AS[/color] store_cnt [color=green]FROM[/color] [color=orange]stores[/color] GROUP BY first_letter [color=green]ORDER BY[/color] store; [!--sql2--][/div][!--sql3--]

I'm not positive but I think if you put [b]SELECT [!--coloro:#FF0000--][span style=\"color:#FF0000\"][!--/coloro--]*[!--colorc--][/span][!--/colorc--][/b]
it just selects all the fields and ignores everything until the word FROM

so try putting in all the fields you want
along with the other to dynamic ones

or at least trying doing just this and see what happens

[!--sql--][div class=\'sqltop\']SQL[/div][div class=\'sqlmain\'][!--sql1--][span style=\'color:blue;font-weight:bold\']SELECT[/span] substring(store,1,1) [color=green]AS[/color] first_letter, [color=blue]count[/color](*) [color=green]AS[/color] store_cnt, name [color=green]FROM[/color] [color=orange]stores[/color] GROUP BY first_letter [color=green]ORDER BY[/color] store; [!--sql2--][/div][!--sql3--]

Share this post


Link to post
Share on other sites
That's what GROUP BY does.

If you "select first_letter, COUNT(*) .... GROUP BY first_letter" then you get a count of records begining with each letter. As you also selected other fields not in the GROUP BY clause, it pulls them from the first record of the group.

If you want all the records then "ORDER BY first_letter, store" and forget the group by.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.