减少同一个表

时间:2018-05-28 18:21:09

标签: mysql join pivot

我有两张桌子:

ranking_history

| user_id | ranking | time
|    1    |  2      | 2018-05-21     
|    1    |  5      | 2018-04-28
|    2    |  9      | 2018-05-21     
|    2    |  1      | 2018-04-28

用户

| id | ranking 
| 1  |  7     
| 2  |  3     

我需要连接这两个表来生成如下所示的表:

| id | ranking | last_weeks_ranking | last_months_ranking 
| 1  |  7      |     2              |    5  
| 2  |  3      |     9              |    1  

这是我尝试过的:

SELECT *, r1.ranking as last_weeks_ranking, r2.ranking as last_months_ranking 
from user 
left join ranking_history r1 on user.id = r1.user_id where r1.time = '2018-05-21' 
left join ranking_history r2 on user.id = r2.user_id where r2.time = '2018-04-28' 

输出正常,但我需要连接一个表两次。有没有更简单的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

其他方法是使用共同相关的子查询:

SELECT 
   user.id, 
   user.ranking,
   (SELECT 
        ranking_history.ranking 
    FROM 
        ranking_history
    WHERE
        ranking_history.user_id = user.id
        AND ranking_history.time >= NOW() - INTERVAL 1 WEEK - INTERVAL 1 DAY
    ORDER BY 
        ranking_history.time ASC
    LIMIT 1) AS last_weeks_ranking,
   (SELECT 
        ranking_history.ranking 
    FROM 
        ranking_history
    WHERE
        ranking_history.user_id = user.id
        AND ranking_history.time >= NOW() - INTERVAL 1 MONTH - INTERVAL 1 DAY
    ORDER BY 
        ranking_history.time ASC    
    LIMIT 1) AS last_months_ranking    
FROM 
    user

PS :我使用固定值'2018-05-21'和'2018-04-28为列last_weeks_rankinglast_months_ranking添加了动态日期计算“

<强>结果

| id | ranking | last_weeks_ranking | last_months_ranking |
+----+---------+--------------------+---------------------+
|  1 |       7 |                  2 |                   5 |
|  2 |       3 |                  9 |                   1 |

参见演示http://sqlfiddle.com/#!9/2f8e2c/9