我有以下 2 个 MySQL 表:
玩家:
| id | name |
|----|---------|
| 1 | Player1 |
| 2 | Player2 |
| 3 | Player3 |
分数:
| key | id | round | score |
|-----|----|-------|-------|
| 1 | 1 | Rd1 | 20 |
| 2 | 1 | Rd2 | 22 |
| 3 | 1 | Rd3 | 19 |
| 4 | 2 | Rd1 | 18 |
| 5 | 2 | Rd2 | 23 |
| 6 | 2 | Rd3 | 19 |
其中scores.id=players.id
我的“玩家”表中将有超过 90 名玩家,查询此表并将其插入 HTML 表以使其更易于查看的最佳方法是什么?我希望有类似这样的输出:
| Player | Round 1 | Round 2 | Round 3 |
|---------|---------|---------|---------|
| Player1 | 20 | 22 | 19 |
| Player2 | 18 | 23 | 19 |
这是我第一次尝试标准化表中的数据。我需要做很多案子吗?我不确定使用 INNER JOIN 转换数据的最佳方法是什么。
最佳答案
这是我的解决方案,希望它有所帮助:
SELECT
name as Player,
SUM(CASE WHEN (s.round='Rd1') THEN s.score ELSE 0 END) AS Round1,
SUM(CASE WHEN (s.round='Rd2') THEN s.score ELSE 0 END) AS Round2,
SUM(CASE WHEN (s.round='Rd3') THEN s.score ELSE 0 END) AS Round3
FROM
players p
JOIN scores s
on s.id=p.id
GROUP BY
name
这将输出:
| Player | Round1 | Round2 | Round3 |
|---------|---------|---------|---------|
| Player1 | 20 | 22 | 19 |
| Player2 | 18 | 23 | 19 |
这个Fiddle供您测试!
关于php - 如何在 PHP 中转换 MySQL INNER JOIN 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49196424/