从表中获取最新的两个不同位置

时间:2016-05-25 07:38:08

标签: mysql

以下是我的表,

enter image description here

  

SELECT DISTINCT(availability_location)as location FROM table_name WHERE user_id ='8'ORDER BY availability_date DESC LIMIT 2

我得到了以下结果

enter image description here

我想要以下结果:

  

2016-05-27 pune

     

2016-05-20伯班克

即。唯一的availability_location以及最新的两个条目。

2 个答案:

答案 0 :(得分:3)

您必须使用GROUP BY

SELECT availability_location as location,
       MAX(availability_date) AS max_date
FROM table_name 
WHERE user_id = '8' 
GROUP BY location
ORDER BY max_date DESC LIMIT 2

答案 1 :(得分:2)

您可以使用GROUP BY并按最长日期排序:

 SELECT t.availability_location
 FROM table_name t 
 WHERE user_id = '8'
 GROUP BY t.availability_location 
 ORDER BY max(s.availability_date) DESC LIMIT 2

输出:

availability_location
---------------------
pune
Burbank

编辑:下次,您应该提到您希望它区分大小写。您可以尝试这样做:

 SELECT t.availability_location 
 FROM table_name t 
 INNER JOIN(SELECT s.availability_location , max(s.availability_date) as max_d
            FROM table_name s
            WHERE s.user_id = '8'
            GROUP BY s.availability_location) t2
  ON(t2.availability_location = t.availability_location AND
     t2.max_d = t.availability_date)
 ORDER BY t.availability_date DESC LIMIT 2