假设我有一个名为manager的表,有3个字段,我有10行。
id AgeGroup name
1 a 1
2 a 2
3 a 3
4 b 4
5 b 5
6 c 6
7 d 7
8 d 8
9 d 9
10 e 10
代码:
$con = mysql_connect("localhost","username","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$query = "SELECT * FROM managers ORDER BY AgeGroup ASC";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
echo'<ul>';
if (mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
echo'<li>'.$row['AgeGroup'].'</li>';
}
}
echo'</ul>';
我希望能够回显agegroup字段,但没有重复。 即输出将是:
a
b
c
d
e
任何帮助将不胜感激
答案 0 :(得分:2)
有几种选择:
SELECT * FROM managers GROUP BY AgeGroup ORDER BY AgeGroup ASC
或
SELECT DISTINCT AgeGroup FROM managers ORDER BY AgeGroup ASC
答案 1 :(得分:2)
在查询中添加GROUP BY子句。
$query = "SELECT * FROM managers GROUP BY AgeGroup ORDER BY AgeGroup ASC";
答案 2 :(得分:1)
基于SQL的解决方案是否有帮助?尝试
SELECT DISTINCT AgeGroup FROM managers ORDER BY AgeGroup ASC
这样您就不需要在PHP代码中进行任何更改。
答案 3 :(得分:0)
使用这个
SELECT AgeGroup FROM managers GROUP BY AgeGroup ORDER BY AgeGroup ASC