使用特定标准MYSQL返回最早的记录

时间:2015-10-14 07:34:29

标签: mysql

我试图从类似于此示例的数据中获取最早的记录:

user_id Criteria_1  Criteria_2  Date
1           1           1       1/1/2015
1           0           1       2/1/2015
1           1           0       3/1/2015
2           0           0       1/1/2015
2           0           1       2/1/2015
2           1           0       3/1/2015

期望的结果:

user_id Criteria_1  Criteria_2  Date
1           1           1       1/1/2015
2           0           1       2/1/2015

a。)user_id应该是唯一的 b。)应满足Criteria_1,Criteria_2的OR c。)最早的日期

3 个答案:

答案 0 :(得分:1)

这是body { -ms-overflow-style: scrollbar; } 标签下最常被问到的问题,但是嘿,这是一个缓慢的日子......

mysql

答案 1 :(得分:0)

试试这个

SELECT user_id, 
 SUBSTRING_INDEX(GROUP_CONCAT(Criteria_1 ORDER BY Date ASC),',',1) AS Crit_1,
 SUBSTRING_INDEX(GROUP_CONCAT(Criteria_2 ORDER BY Date ASC),',',1) AS Crit_2,
 SUBSTRING_INDEX(GROUP_CONCAT(Date ORDER BY Date ASC),',',1) AS date_unformat,
 SUBSTRING_INDEX(GROUP_CONCAT(DATE_FORMAT(Date,'%d/%m/%Y') ORDER BY Date ASC),',',1) AS date_format
 FROM table
 WHERE Criteria_1 =1 OR Criteria_2 =1 
 GROUP BY user_id
 ORDER BY user_id

我添加了两种格式的日期。您可以使用适用于您的结果的

答案 2 :(得分:0)

假设您的日期为VARCHARTEXT类型,则可以执行此操作

SELECT *
FROM `table` AS a
WHERE STR_TO_DATE(`date`, '%d/%m/%Y') = (SELECT MIN(STR_TO_DATE(`date`, '%d/%m/%Y')) FROM table AS b WHERE b.user_id = a.user_id AND  (criteria_1 = 1 OR criteria_2 = 1) )
GROUP BY user_id