在我的表中
names countries scores
[id -- FirstName -- LastName] [id -- cid -- Country] [id -- sid -- Score]
[1 -- FName1 -- LName1 ] [1 -- 1 -- USA ] [1 -- 1 -- 5]
[2 -- FName2 -- LName2 ] [2 -- 1 -- France ] [2 -- 1 -- 6]
[3 -- FName3 -- LName3 ] [3 -- 1 -- Germany] [3 -- 2 -- 7]
[4 -- FName1 -- LName1 ] [4 -- 2 -- Germany] [4 -- 2 -- 8]
[5 -- 2 -- Czech ] [5 -- 2 -- 2]
[6 -- 3 -- Germany] [6 -- 4 -- 12]
[7 -- 4 -- Czech ] [7 -- 3 -- 15]
我获取数据并在此结构中进行
.Container div {
border: 1px solid blue;
margin: 10px;
}
.Container div div {
border: 1px solid red;
margin: 10px;
}
<div>
<div id="Master German">German</div>
<div id="German">
<div class="Container">
<div id='FName2 German'>
<div>FName2</div>
<div>LName2</div>
</div>
<div id='FName1 German'>
<div>FName1</div>
<div>LName1</div>
</div>
<div id='FName3 German'>
<div>FName3</div>
<div>LName3</div>
</div>
</div>
</div>
<div id="Master France">France</div>
<div id="France">
<div class="Container">
<div id='FName1 France'>
<div>FName1</div>
<div>LName1</div>
</div>
</div>
</div>
<div id="Master Czech">Czech</div>
<div id="Czech">
<div class="Container">
<div id='FName4 Czech'>
<div>FName4</div>
<div>LName4</div>
</div>
<div id='FName2 Czech'>
<div>FName2</div>
<div>LName2</div>
</div>
</div>
</div>
<div id="Master USA">USA</div>
<div id="USA">
<div class="Container">
<div id='FName1 USA'>
<div>FName1</div>
<div>LName1</div>
</div>
</div>
</div>
</div>
使用以下查询
SELECT
a.FirstName,
a.LastName,
c.Country,
SUM(b.Scores) AS Score
FROM names a
INNER JOIN countries c
ON a.id = c.cid
LEFT JOIN scores b
ON a.id = b.sid
WHERE a.id = :id
GROUP BY a.id
ORDER BY Score ASC
现在我的问题出现在例如id[1]
和id[4]
具有相同的FName
和LName
,但得分不同
因为我按Score
和id[4]
&gt; id[1]
结构应该像
Germany:
FName2 -- LName2 [Score: 15]
FName3 -- LName3 [Score: 15]
FName1 -- LName1 [Score: 11]
Czech:
FName2 -- LName2 [Score: 15]
FName1 -- LName1 [Score: 12]
但我得到的是
Germany:
FName2 -- LName2 [Score: 15]
FName3 -- LName3 [Score: 15]
Czech:
FName2 -- LName2 [Score: 15]
FName1 -- LName1 [Score: 12]
Germany:
FName1 -- LName1 [Score: 11]
我尝试了所有可能的group by
但没有任何效果总是有额外的country
div
我的PHP代码是
$pre = null;
echo "<div>";
$end = "";
while ($row = $stmt->fetch()) {
$FName = $row['FirstName'];
$LName = $row['LastName'];
$Country = $row['Country'];
if ($Country != $pre) {
echo $end;
echo "<div id='Master $Country'>$Country</div>";
echo "<div id='$Country'>";
}
$end = "</div>
</div>";
$pre = $Country;
echo "
<div id='$FName USA'>
<div>$FName</div>
<div>$LName</div>
</div>";
}
echo $end;
echo "</div>";
答案 0 :(得分:1)
按国家/地区排序,然后得分:
SELECT
a.FirstName,
a.LastName,
c.Country,
SUM(b.Scores) AS Score
FROM names a
INNER JOIN countries c
ON a.id = c.cid
LEFT JOIN scores b
ON a.id = b.sid
WHERE a.id = :id
GROUP BY a.id
ORDER BY c.Country, Score ASC