SQL查询“几乎”重复条目(最后3列的值相同)

时间:2012-05-29 19:03:09

标签: mysql sql

我需要SQL-Query的帮助。我有一个包含许多条目的表,我想查询最后3列具有相同值的所有条目。

我的表格如下:

|Refrigator|98C08A|2011-08-06 00:00:30|126|126
|Refrigator|B7BE29|2011-08-06 00:00:30|73|70
|Refrigator|599393|2011-08-06 00:00:30|126|126
|Refrigator|B7BE29|2011-08-06 00:00:29|73|70
|Refrigator|599393|2011-08-06 00:00:29|126|126
|Refrigator|599393|2011-08-06 00:00:29|126|126
|Refrigator|98C08A|2011-08-06 00:00:29|126|126
|Refrigator|98C08A|2011-08-06 00:00:29|126|126
|Refrigator|599393|2011-08-06 00:00:28|126|126

所以我想得到所有的行,它们对于最后3列具有完全相同的值,因此结果应如下所示:

|Refrigator|98C08A|2011-08-06 00:00:30|126|126
|Refrigator|599393|2011-08-06 00:00:30|126|126
|Refrigator|599393|2011-08-06 00:00:29|126|126
|Refrigator|599393|2011-08-06 00:00:29|126|126 (if possible without this duplicate)
|Refrigator|98C08A|2011-08-06 00:00:29|126|126
|Refrigator|98C08A|2011-08-06 00:00:29|126|126 (if possible without this duplicate)

有谁知道如何管理这个? 到目前为止我尝试的是:

SELECT * 
FROM smtab 
WHERE Datetime IN (
      SELECT Datetime 
      FROM smtab 
      GROUP BY Datetime 
      HAVING count(Datetime) >1) 
AND Power1 IN (
      SELECT Power1 
      FROM smtab 
      GROUP BY Power1 
      HAVING count(Power1) >1) 
AND Power8 IN (
      SELECT Power8 
      FROM smtab 
      GROUP BY Power8 
      HAVING count(Power8) >1) 
ORDER BY Datetime DESC;

但我没有工作!!!

希望有人可以帮助我! thx提前...

4 个答案:

答案 0 :(得分:1)

SELECT DISTINCT *
FROM   smtab NATURAL JOIN (
  SELECT   Datetime, Power1, Power8
  FROM     smtab
  GROUP BY Datetime, Power1, Power8
  HAVING   COUNT(*) > 1
) AS t

答案 1 :(得分:0)

我相信您正在寻找自我加入。看看this SO answer即可开始使用。您没有提到要排除的列,因此我无法提供任何代码。

答案 2 :(得分:0)

您的问题是您需要识别重复项,内部联接,然后找到匹配的所有内容。

distinct只能返回每个副本中的一个。

-- only select one of each duplicate.
select distinct *
  from smtab as a
        -- Find the duplicates
  join ( select datetime, power1, power8
           from smtab
          group by datetime, power1, power8
         having count(*) > 1) as b
      -- join back on to the main table
    on a.datetime = b.datetime
   and a.power1 = b.power1
   and a.power8 = b.power8

您正在寻找所有3列的副本,而不是单独的每一列。因此,您必须同时对所有3个进行分组才能找到您的副本。

答案 3 :(得分:0)

这种方法适用于我的数据模型,使用SQL Server。不确定它是否适用于MySQL。我正在将表连接到派生查询。派生查询查找具有>的所有记录1条记录。

select * from Employees as e
 inner join
(
select LastName, firstname from Employees 
 group by LastName, FirstName having COUNT(1) > 1
) as derived
on e.LastName = derived.lastname and e.FirstName = derived.firstname
order by e.LastName

编辑: 要使其与您的数据模型更相关,请尝试以下方法:

SELECT * FROM smtab as s
  inner join 
(
  select datetime, power1, power8 
    from smtab as s2
   group by s2.datetime, power1, POWER8 having COUNT(1) > 1
) as derived
on s.datetime = derived.datetime and s.power1 = derived.power1 
and s.power8 = derived.power8
ORDER BY Datetime DESC;