简体   繁体   English

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

[英]Get latest two distinct location from table

Below is my table, 下面是我的桌子,

在此处输入图片说明

SELECT DISTINCT(availability_location) as location FROM table_name WHERE user_id = '8' ORDER BY availability_date DESC LIMIT 2 从表名WHERE user_id ='8'中选择DISTINCT(availability_location)作为位置ORDER BY Availability_date DESC LIMIT 2

I'm getting following result 我得到以下结果

在此处输入图片说明

I want following result : 我想要以下结果:

2016-05-27 pune 2016-05-27浦那

2016-05-20 Burbank 2016-05-20伯班克

ie Unique availability_location as well as latest two entries. 即唯一的availability_location以及最近的两个条目。

You have to use GROUP BY for this: 您必须为此使用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

You can use GROUP BY and order by the max date : 您可以使用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

Output : 输出:

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

EDIT: next time, you should mention that you want it to be case sensitive. 编辑:下次,您应该提到您希望它区分大小写。 You can try doing it like this: 您可以尝试这样做:

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM