MySQL选择每个客户的最新调查分数

MySQL选择每个客户的最新调查分数,mysql,views,inner-join,Mysql,Views,Inner Join,简单地说,我有一张如下所示的桌子: 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_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
该视图仅从每个客户中选择最新的调查分数

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

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

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
SELECT customer_id, 
SUBSTRING_INDEX(GROUP_CONCAT(score ORDER BY `date` DESC), 1) AS latest_score
FROM customer_surveys
GROUP BY customer_id
使用该函数可以获取分隔字符串的第一项

@juergen-d之前的回答肯定也会起作用