mysql - 如何根据 MySQL 中的 2 列删除将与上一行值匹配的下一行值

标签 mysql sql

我需要帮助,我想知道如何从 2 列中删除与 MySQL 表库上的前一行或列值匹配的下一行或列值。

因此,如果下一行/列值/结果包含与前一行/列值/结果相同的值,它将被删除,但如果下一列与前一列值/结果不匹配,该行不应被删除。该条件的正确查询是什么?

我尝试首先进行选择查询,以验证数据,这是我的选择查询。我的查询适合选择吗?

SELECT current_row.row, current_row.id, current_row.column1,
       current_row.column2, previous_row.row, previous_row.id,
       previous_row.column1, previous_row.column2 
FROM 
   (SELECT  @rownum:=@rownum+1 row, a.*    
    FROM MyTable a, (SELECT @rownum:=0) r 
    ORDER BY unix_time, id 
   ) as current_row 

LEFT JOIN  
   (SELECT @rownum2:=@rownum2+1 row, a.*    
    FROM MyTable a, (SELECT @rownum2:=0) r
   ORDER BY unix_time, id) as previous_row 

ON (current_row.id = previous_row.id) 
AND (current_row.column1 = previous_row.column1) 
AND (current_row.column2 = previous_row.column2) 
AND (current_row.row = previous_row.row - 1) 
LIMIT 10;

提前非常感谢您的帮助!

干杯!

最佳答案

我们正在尝试选择具有分配的新虚拟id的数据进行比较,因此ON子句应为t1.myid =t2.myid+1WHERE 子句应过滤 col1col2 行:

 SET @id1:=0 , @id2:=0 ;
 SELECT * FROM (
      (SELECT *, @id1:=@id1+1 as myid from mytable ) as t1
 LEFT JOIN
      (SELECT *, @id2:=@id2+1 as myid from mytable ) as t2
 ON  t1.myid = t2.myid + 1
 )
 WHERE t1.col1= t2.col1 and t1.col2 = t2.col2

对于 DELETE 命令,您应该将结果保存在临时表中,然后删除其 id 存储在临时表中的行:

 SET @id1:=0 , @id2:=0 ;
 CREATE TEMPORARY TABLE tbl_ids AS 
 SELECT t1.id FROM ( -- t1.id returns NEXT row
      (SELECT *, @id1:=@id1+1 as myid from mytable ) as t1
 LEFT JOIN
      (SELECT *, @id2:=@id2+1 as myid from mytable ) as t2
 ON  t1.myid = t2.myid + 1 -- t1.myid > t2.myid
 )
 WHERE t1.col1= t2.col1 and t1.col2 = t2.col2 ;

 DELETE FROM mytable WHERE id in (SELECT * FROM tbl_ids) ;

关于mysql - 如何根据 MySQL 中的 2 列删除将与上一行值匹配的下一行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42319572/

相关文章:

php - 在php中获取包含美元字符的PDO结果集

php - 更新页面 View

php - MySQL 查询 : Getting COUNT of one table where the ID of table 1 has a value of X in a different table

MySQL 如果存在则

SQL - 为这个简单查询创建条件 Where 子句

sql - 如何清理 C 或 Objective-C 中的数据库输入?

mysql - SQL在预订系统中查找连续两天

php - MySQL 匹配与喜欢

c# - C# 应用程序中的错误 [42000] MySQL

php - 在 MySql 中生成查询