php - 如何在 PHP 中转换 MySQL INNER JOIN 结果?

标签 php mysql inner-join

我有以下 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/

相关文章:

php - 向文本/普通电子邮件添加换行符 (\r\n\r\n )

mysql - 从 MySql 导出到 sql 文件时如何自动转义内容中的引号?

php - 我应该使用哪个索引来混合 WHERE 和 ORDER BY

PHP mysql_num_rows() 在 INNER JOIN 查询中的用法

mysql - 在mysql中使用内连接语法更新表

php - 如何确保我的赞按钮只被用户按下一次?

php - 在 YII2 框架中为 css 创建绝对 url

php - PHP 中的连接被拒绝错误

mysql - 如何在Rails中通过seed.rb从yaml文件中种子连接表数据

doctrine - Symfony Doctrine_Query用INNER JOIN删除