开发者

Group By name Order By name returns all letters

For some reason this query isnt working.

<p align="center">
<?php
$result1 = mysql_query("SELECT name FROM comics GROUP BY name ORDER BY name ASC");
while ($row = mysql_fetch_array($result1))
{
?>
<a href="?sort=<?php echo substr($row['name'], 0, 1); ?>"><?php echo substr($row['name'], 0, 1); ?></a>&nbsp;    
<?ph开发者_运维技巧p } ?>    
</p> 

The Output

2  2  3  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  A  V  V  V  V  Z  

instead of it going through and grouping by the name and then breaking it down by first letter and just displaying one letter it displays them all.

any help?


You GROUP BY the full name in SQL; than you iterate the result in PHP and display the first letter only; of course if your table contains e.g.

Abc Ade Afg

GROUP BY name would return them all; and displaying only the first letter will print "A" three times.

If you only want to retrieve the first letters you could try

SELECT
 LEFT( name, 1 ) AS fl 
FROM 
 ...
GROUP BY
 fl


Your query worked just fine. You asked for all names of all comics and grouped them by name ascending. The problem is you just wanted to group the first letter of your comics names.

SELECT LEFT(`name`,1) AS 'part'
FROM `comics`
GROUP BY LEFT(`name`,1)
ORDER BY LEFT(`name`,1) ASC;

In php it is now enough to echo $row['part'];


SELECT SUBSTRING(name,1) as name FROM comics GROUP BY 1 ORDER BY 1 ASC


How many distinct names do you have in the database. You are doing a substring on the results returned so that if you were returned a set of names such as:

adam
andy
abraham
alfie

You would end up with

a
a
a
a

Using

SELECT distinct(name) FROM comics ORDER BY name ASC

will return the unique names in ascending numerical order fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜