根据重复的列删除整行。

huangapple go评论90阅读模式
英文:

removing an entire row based on an duplicate column

问题

你可以使用以下SQL语句来删除基于重复时间戳的整行数据:

DELETE t1 FROM tblname t1
INNER JOIN tblname t2
WHERE t1.timestamp_column = t2.timestamp_column
AND t1.id < t2.id;

这将删除具有重复时间戳的行,只保留其中一行。

英文:

Let's say I have a Mysql table that contains timestamps, ids, and a few more parameters.
How can I remove an entire row based on duplicate timestamps?

SELECT DISTINCT COL_NAME From tblname, will return 1 column with my timestamps filtered, but I need to actually remove them from my table (The Entire row).

Thanks!

答案1

得分: 0

根据我的意见,首先找到重复的时间戳数据行。在找到重复行之后,您可以删除其中一行重复行。如果您希望删除具有相同时间戳值的行组中的最小id,这是我的建议代码。这段代码是子查询的组合。

CREATE TEMPORARY TABLE tmp_table AS ( -- 创建临时表
  SELECT MIN(id) AS id_to_keep
  FROM tblname
  GROUP BY timestamp_col
  HAVING COUNT(*) > 1
);

DELETE FROM tblname
WHERE id NOT IN (SELECT id_to_keep FROM tmp_table);

请注意,这是SQL代码,用于查找和删除具有重复时间戳的行。

英文:

According to my opinion first find the Duplicate timestamps data rows. After find the duplicate rows , you can delete one of the duplicate row. If you like to delete smallest id for each group of rows with the same timestamp value this is my suggest code. This is code is combination of subqueries.

  CREATE TEMPORARY TABLE tmp_table AS ( // create temp table
  SELECT MIN(id) AS id_to_keep
  FROM tblname
  GROUP BY timestamp_col
  HAVING COUNT(*) &gt; 1
);

DELETE FROM tblname
WHERE id NOT IN (SELECT id_to_keep FROM tmp_table);

huangapple
  • 本文由 发表于 2023年5月7日 14:15:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定