Jump to content

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
} ?>
Link to comment
https://forums.phpfreaks.com/topic/8841-alphabetical-index-using-group-by/
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--]
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.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.