2

我需要有关 SQL 查询的帮助。我有一个包含许多条目的表,我想查询最后 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;

但我没有工作!!!

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

4

4 回答 4

1
SELECT DISTINCT *
FROM   smtab NATURAL JOIN (
  SELECT   Datetime, Power1, Power8
  FROM     smtab
  GROUP BY Datetime, Power1, Power8
  HAVING   COUNT(*) > 1
) AS t
于 2012-05-29T19:08:15.567 回答
0

我相信你正在寻找一个自我加入。看看这个 SO answer开始。您没有提及您希望排除哪些列,因此我无法提供任何代码。

于 2012-05-29T19:07:23.260 回答
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 个进行分组才能找到您的重复项。

于 2012-05-29T19:07:53.407 回答
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;
于 2012-05-29T19:12:51.807 回答