ctn8iv Posted May 1, 2006 Share Posted May 1, 2006 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} ?> Link to comment https://forums.phpfreaks.com/topic/8841-alphabetical-index-using-group-by/ Share on other sites More sharing options...
Zane Posted May 1, 2006 Share Posted May 1, 2006 [!--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 FROMso try putting in all the fields you wantalong with the other to dynamic onesor 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--] Link to comment https://forums.phpfreaks.com/topic/8841-alphabetical-index-using-group-by/#findComment-32450 Share on other sites More sharing options...
Barand Posted May 1, 2006 Share Posted May 1, 2006 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. Link to comment https://forums.phpfreaks.com/topic/8841-alphabetical-index-using-group-by/#findComment-32478 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.