道歉,如果我没有详细解释我的情况,因为我不是母语人士。我相信这对大多数人来说相当简单,但我很挣扎。我正在使用php / mysql。
假设我有一个数据库如下:
id game scorer
1 1 molly
2 1 sarah
3 1 angela
4 1 molly
5 2 jane
6 2 molly
7 2 sarah
我如何编写一个查询来展示每场比赛的得分手数,以及他们在赛季结束前得分的目标数量直到该特定目标?
Example:
Game 1: Molly (1st), Sarah (1st), Angela (1st), Molly (2nd)
Game 2: Jane (1st), Molly (3rd), Sarah (2nd)
答案 0 :(得分:2)
CREATE TABLE goals
(goal_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,game INT NOT NULL
,scorer VARCHAR(12) NOT NULL
);
INSERT INTO goals VALUES
(1,1,'molly'),
(2,1,'sarah'),
(3,1,'angela'),
(4,1,'molly'),
(5,2,'jane'),
(6,2,'molly'),
(7,2,'sarah');
SELECT game, GROUP_CONCAT(CONCAT(scorer,'(',rank,')')) scorers FROM
(
SELECT x.game
, x.scorer
, COUNT(*) rank
FROM goals x
JOIN goals y
ON y.scorer = x.scorer
AND y.goal_id <= x.goal_id
GROUP
BY x.game,x.goal_id,x.scorer
)n
GROUP BY game;
+------+--------------------------------------+
| game | scorers |
+------+--------------------------------------+
| 1 | molly(1),sarah(1),angela(1),molly(2) |
| 2 | jane(1),molly(3),sarah(2) |
+------+--------------------------------------+
子查询本身将提供替代显示
答案 1 :(得分:0)
试试这个,
<?php
$query="SELECT * FROM `goals`";
$result = mysqli_query($query);
$goals_scored = array();
$scorer_goals = array();
while($row=mysqli_fetch_array($result)){
$score = array('scorer'=>$row['scorer']);
if(isset($scorer_goals[$row['scorer']])){
$scorer_goals[$row['scorer']]++;
$score['goal_number']=$scorer_goals[$row['scorer']];
array_push($goals_scored[$row['game']], $score);
}
else{
$scorer_goals[$row['scorer']] = 1;
$score['goal_number']=$scorer_goals[$row['scorer']];
$goals_scored[$row['game']] = array($score);
}
}
echo '<table>';
foreach($goals_scored as $key=>$goals){
echo '<tr><td>Game '.$key.'</td>';
foreach($goals as $goal){
echo '<td>'.$goal['scorer'].'( '.$goal['goal_number'].' )</td>';
}
echo '</tr>';
}
echo '</table>';
?>