我在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上),只有当每个重复项的日期字段之间的时间少于或等于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 list all duplicates on a specific field and only if day between another field date <= 1
最后一个答案解决了我的问题:
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
);
现在我想用更复杂的标准应用相同的查询,如果子句WHERE只是&#34;其中t.car_num = t2.car_num&#34;则前一个请求有效。但现在我想比较更复杂的标准:UPPER(REPLACE(更换(car_num,&#39;&#39;&#39;&#39;),&#39; - &#39;, &#39;&#39;))不直接在car_num上。我尝试用函数传递param&#34;其中reduce_num(t.car_num)= reduce_num(t2.car_num)&#34;但查询进入无限循环。有什么想法吗?
感谢任何帮助
答案 0 :(得分:1)
尝试将函数放在字段car_num中的单独SELECT语句中,如下所示:
select t.* from
(
select *, replace(replace(car_num,' ',''),'-','') reduce_num from mytable
) t
where exists
(
select 1 from
(
select *, replace(replace(car_num,' ',''),'-','') reduce_num from mytable
) t2
where (t.reduce_num = t2.reduce_num) and
(t.id <> t2.id) and
(abs(datediff(t2.datum, t.datum)) <= 1)
);