我在MySQL“mytable”中有一个表格,如下所示:
id car_num date
----- -------- -----------
00001 BBB 2015-09-28
00002 BBB 2015-10-04
00003 DDD 2015-10-04
00004 BBB 2015-10-04
00005 AAA 2015-10-05
00006 GGG 2015-10-05
00007 GGG 2015-10-05
00009 EEE 2015-10-06
00010 AAA 2015-10-06
00011 HHH 2015-10-10
00012 FFF 2015-10-11
00013 FFF 2015-10-11
00014 CCC 2015-10-13
这是我的查询显示所有重复项(字段car_num):
SELECT a.*
FROM mytable a
INNER JOIN
(
SELECT car_num
FROM mytable
GROUP BY car_num
HAVING COUNT(car_num) >= 2
) b ON a.car_num = b.car_num
ORDER BY car_num ASC
结果是:
id car_num date
----- -------- -----------
00005 AAA 2015-10-05
00010 AAA 2015-10-06
00001 BBB 2015-09-28
00002 BBB 2015-10-04
00004 BBB 2015-10-04
00012 FFF 2015-10-11
00013 FFF 2015-10-11
00006 GGG 2015-10-05
00007 GGG 2015-10-05
现在我只想在每个重复项的日期字段之间存在少于或等于1天的情况下显示重复项,并且我想按日期DESC订购它们
我的期望:
id car_num date
----- -------- -----------
00012 FFF 2015-10-11
00013 FFF 2015-10-11
00010 AAA 2015-10-06
00005 AAA 2015-10-05
00006 GGG 2015-10-05
00007 GGG 2015-10-05
00002 BBB 2015-10-04
00004 BBB 2015-10-04
是否可以直接使用MySQL查询(带有DATEDIFF的东西)?任何帮助表示赞赏
答案 0 :(得分:0)
您可以这样做:
select t.*
from mytable t
where exists (select 1
from mytable t2
where t.car_num = t2.car_num and
t.id <> t2.id and
abs(datediff(t2.date, t.date)) <= 1
);