Jump to content


Photo

Alphabetical Index using GROUP BY


  • Please log in to reply
2 replies to this topic

#1 ctn8iv

ctn8iv
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 01 May 2006 - 07:56 PM

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
} ?>

#2 Zane

Zane
  • Administrators
  • Advanced Member
  • 4,134 posts

Posted 01 May 2006 - 08:09 PM

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

I'm not positive but I think if you put SELECT [!--coloro:#FF0000--][span style=\"color:#FF0000\"][!--/coloro--]*[!--colorc--][/span][!--/colorc--]
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) AS first_letter, count(*) AS store_cnt, name FROM stores GROUP BY first_letter ORDER BY store; [!--sql2--][/div][!--sql3--]

btn_donate_SM.gif Want to thank me? Contribute to my PayPal piggy-bank
 

172938.png

#3 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 01 May 2006 - 10:55 PM

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.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users