从 mysql 表中检索所有行,但首先将它们分组以删除重复
Posted
技术标签:
【中文标题】从 mysql 表中检索所有行,但首先将它们分组以删除重复【英文标题】:retrieve all rows from mysql table but group them first to remove duplication 【发布时间】:2014-04-20 00:23:18 【问题描述】:我正在从表中检索所有记录以在 php 页面上回显它们,问题是表中重复的 3 列具有相似值的行,有人可以帮我写这段代码吗?我需要分组什么?该组仅检索到一行,请回复。分组的字段越来越重复,添加新记录的字段是secondarySubject和secondaryGrade
我得到的结果是:
---------------------------------
2012-2013 School ABC A-Level
in science A
2012-2013 School ABC A-Leve
in maths B
2012-2013 School ABC A-Level
in Eng C
-----------------------------------
我想要的是
----------------
2012-2013 School ABC A-Level
in science A
in maths B
in Eng C
-----------------------
$result2 = $db->query('
SELECT *
FROM secondaryEducation
WHERE userID = "'.$graduateID.'"
ORDER BY secondaryFinishDate DESC
');
$html .= '<h2>Secondary Education: '.$option.'</h2>';
while($row = mysql_fetch_assoc($result2))
$startYear = formatDate($row['secondaryStartDate'], 'Y');
$finishYear = formatDate($row['secondaryFinishDate'], 'Y');
if (!empty($row['secondaryGrade']))
$secondaryGrade = getSecondaryGradeName($row['secondaryGrade']);
else
$secondaryGrade = $row['secondaryGradeCustom'];
if (!empty($row['secondarySubject']))
$secondarySubject = getSecondarySubjectName($row['secondarySubject']);
else
$secondarySubject = $row['secondarySubjectCustom'];
$score = $row['score'];
$secondaryLevel = getSecondaryLevelName($row['secondaryLevel']);
$levelID = getSecondaryLevelID($row['secondaryLevel']);
if($levelID!=='7')
$html .= '
<div class="secondaryListing">
<div><strong>'.$startYear.' - '.$finishYear.' '.stripslashes($row['secondarySchool']).'</strong></div>
<div>'.$secondaryLevel.' in '.$secondarySubject.' - '.stripSlashes($secondaryGrade).'</div>
</div><!-- End education listing -->';
【问题讨论】:
考虑提供适当的 DDL(和/或 sqlfiddle)以及所需的结果集。 请提供一些示例数据。 我有,请告诉我 提供for循环的php代码——$html .= '
之前的代码
试图理解。您是说您有多行带有2012-2013 School ABC A-Level
吗?但你只想看一次?
【参考方案1】:
就在while循环之前,创建一个数组:
$schools = array();
while($row = mysql_fetch_assoc($result2))
...
不是附加到$html
,而是将字符串添加到$schools
关联数组:
if($levelID!=='7')
$schools[$startYear.' - '.$finishYear.' '.stripslashes($row['secondarySchool']) . ' ' . $secondaryLevel][]=' in '.$secondarySubject.' - '.stripSlashes($secondaryGrade);
最后,迭代$schools
关联数组并将字符串附加到$html
:
foreach($schools as $group => $entries)
$html .= '<div class="secondaryListing"><div><strong>'.$group.'</strong></div>';
foreach($entries as $entry)
$html .= '<div>'.$entry.'</div>';
$html .='</div><!-- End education listing -->';
【讨论】:
OH MY GOD,它成功了,非常感谢,最后一件事拜托eeeeeeeeeeeeee,secondaryLevel 仍在重复,请问我怎样才能让它也出现一次? 我编辑了答案 - 在if($levelID!=='7')
分配中,我将变量 $secondaryLevel
从右侧移动到左侧(从“条目”到“组”)
oops 刚刚意识到这些条目是重复的 :( 有什么具体原因吗?
这就像如果有 4 行它被打印 4 次,最初有一条记录,然后是 2,直到 4
你的意思是' in '.$secondarySubject.' - '.stripSlashes($secondaryGrade)
被包含在多个组中?以上是关于从 mysql 表中检索所有行,但首先将它们分组以删除重复的主要内容,如果未能解决你的问题,请参考以下文章