【问题标题】:MySQL select most recent survey score per customerMySQL 选择每个客户的最新调查分数
【发布时间】:2013-05-18 01:55:39
【问题描述】:

简单地说,我有一个如下所示的表格:

customer_surveys
----------------
id | customer_id | score | date
1  |           1 |     5 | 01-01-2013     
2  |           1 |     6 | 01-02-2013  
3  |           2 |     8 | 01-03-2013   
4  |           2 |     7 | 01-04-2013

我想创建一个如下所示的视图:

customer_survey_scores
----------------------
customer_id | score
1           | 6
2           | 7

视图只是从每个客户那里选择最近的调查分数。

我可以通过编写一个复杂的子查询来实现这一点,但需要它尽可能快地执行。

【问题讨论】:

    标签: mysql views inner-join


    【解决方案1】:
    select c.customer_id, c.score
    from customer_surveys c
    inner join 
    (
      select customer_id, max(date) as mdate
      from customer_surveys 
      group by customer_id
    ) x on x.customer_id = c.customer_id and x.mdate = c.date
    

    【讨论】:

      【解决方案2】:

      GROUP_CONCAT 可用于获取组内的有序数据:

      SELECT customer_id, 
      SUBSTRING_INDEX(GROUP_CONCAT(score ORDER BY `date` DESC), 1) AS latest_score
      FROM customer_surveys
      GROUP BY customer_id
      

      使用SUBSTRING_INDEX 函数可以获得分隔字符串的第一项。

      @juergen-d 之前的回答肯定也可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多