MYSQL - find and show all duplicates within date difference critria

一个人想着一个人 提交于 2019-12-12 00:33:09

问题


This query below selects all rows that have a row with the same father registering 335 days or less since earlier registration. Is there a way to edit this query so that it does not eliminate the duplicate row in the output? I need to see all instances of the registration for that father within 335 days of each other.

SELECT * FROM ymca_reg a later
WHERE NOT EXISTS (
    SELECT 1 FROM ymca_reg a earlier 
    WHERE 
        earlier.Father_First_Name = later.Father_First_Name
        AND earlier.Father_Last_Name = later.Father_Last_Name
        AND (later.Date - earlier.Date < 335) AND (later.Date > earlier.Date)

My current query is:

SELECT ymca_reg.* FROM ymca_reg WHERE (((ymca_reg.Year) In (SELECT Year FROM ymca_reg As Tmp 
    GROUP BY Year, Father_Last_Name, Father_First_Name 
    HAVING Count(*)>1  
        And Father_Last_Name = ymca_reg.Father_Last_Name 
        And Father_First_Name = ymca_reg.Father_First_Name))) 
    ORDER BY ymca_reg.Year, ymca_reg.Father_Last_Name, ymca_reg.Father_First_Name 

This query does return all the duplicates for review correctly, but it's terribly slow because it doesn't use a join and as soon as I add the date criteria it only returns the later row. Thanks.


回答1:


I think you want something like this:

SELECT *
FROM ymca_reg later
WHERE EXISTS (SELECT 1
              FROM ymca_reg earlier 
              WHERE earlier.Father_First_Name = later.Father_First_Name AND
                    earlier.Father_Last_Name = later.Father_Last_Name AND
                    abs(later.Date - earlier.Date) < 335 and
                    later.Date <> earlier.Date
             );

This should return all records that have such duplicates. Note that "later" and "earlier" are no longer really apt descriptions, but I left the names so you can see the similarity to your query.



来源:https://stackoverflow.com/questions/32414978/mysql-find-and-show-all-duplicates-within-date-difference-critria

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!