簡體   English   中英

如何在PHP中透視MySQL INNER JOIN結果?

[英]How do I pivot MySQL INNER JOIN results in PHP?

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

這個小提琴供您測試!

我有一個更明智的替代解決方案,它使用子查詢,具有以下好處:沒有得分的玩家也會被列出!!

    SELECT
     p.name,  
    ifnull((select score from scores where id = p.id and round='Rd1' limit 1), 0) as Round1,
    ifnull((select score from scores where id = p.id and round='Rd2' limit 1), 0) as Round2,
    ifnull((select score from scores where id = p.id and round='Rd3' limit 1), 0) as Round3
FROM  players p        
GROUP BY p.name, p.id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM