MySQL

时间:2017-01-05 13:47:12

标签: mysql

我正在实现一项功能,我必须根据同一个表的下一行中的值删除当前行。

我有列的记录:idcreated_atmark

我需要删除所有记录,

WHERE currentrow.mark != nextrow.mark or (currentrow.mark = nextrow.mark and currentrow.created_at= '2000-01-01 00:00:00.000')

即。只有下一行的记录没有相同的标记或下一行的记录具有相同的标记和created_at = '2000-01-01 00:00:00.000'

id      created_at                  mark
235    1990-01-01 00:00:00.000      5                  /delete
236    1990-01-01 00:00:00.000      5                  /delete
237    1990-01-01 00:00:00.000      5
238    2016-10-10 23:45:40.000      5


id       created_at                 mark
312    1990-01-01 00:00:00.000      8                  /delete
313    2016-01-09 18:00:00.000      6                  
314    1990-01-01 00:00:00.000      4                  /delete
315    1990-01-01 00:00:00.000      7
316    2016-10-10 23:45:40.000      7

请帮助检索每一行在结果集中水平连接相同表格的下一行的表格。

2 个答案:

答案 0 :(得分:2)

加入下一行的一种方法是

INNER JOIN `tablename` AS `next` ON `next`.`id` = (
  SELECT MIN(id) FROM `tablename` WHERE `tablename`.`id` > `current`.`id`
)
AND (`next`.`mark` != `current`.`mark` 
  OR `next`.`created_at` = '2000-01-01 00:00:00.000') // maybe 1990?

答案 1 :(得分:2)

我完全不了解删除条件。但我会回答你的最后一个问题 "请帮助检索每一行在结果集中水平连接相同表格的下一行的表格。"

SELECT * FROM 
(SELECT (@rowid1 := @rowid1 + 1) firstSeq, id firsttableid, created_at firsttablecreated_at, mark firsttablemark FROM `mytable`
JOIN (SELECT @rowid1 := 0) a) table1
LEFT JOIN (SELECT (@rowid2 := @rowid2 + 1) secondSeq, id secondtableid, created_at secondtablecreated_at, mark secondtablemark FROM `mytable`
JOIN (SELECT @rowid2 := 0) a) table2 ON table1.firstSeq = table2.secondSeq - 1 and **(your conditions)**

这将根据您的需要为您提供结果集。现在您可以添加转换为删除所需的条件