如何删除重复的行但保留最后一行。
Name Surname Value Date
A AA 2 2014-10-01
B BB 5 2014-12-01
C CC 9 2015-07-01
D DD 9 2016-10-01
E EE 9 2014-10-25
Name Surname Value Date
C CC 9 2015-07-01
D DD 9 2016-10-01
E EE 9 2014-10-25
Name Surname Value Date
D DD 9 2016-10-01
答案后更新的代码,目标已实现。 感谢所有受访者。 我希望这对某人有用。
<?php
include("conf.php");
$table = "tables123";
$query = "SELECT Name FROM " . $table;
$resultat = mysqli_query($conn,$query);
if(empty($resultat)) {
echo "<p>" . $table . " table does not exist</p>";
$query = mysqli_query($conn,"CREATE TABLE IF NOT EXISTS $table (
Name varchar(255) NOT NULL,
Surname varchar(255) NOT NULL,
Value varchar(255) NOT NULL,
Date varchar(255) NOT NULL
)CHARACTER SET utf8 COLLATE utf8_general_ci");
}
else {
echo "<p>" . $table . "table exists</p>";
} // else
$sql = "INSERT INTO $table (Name, Surname, Value, Date)
VALUES
('A', 'AA', 2, '2014-10-01'),
('B', 'BB', 5, '2014-12-01'),
('C', 'CC', 9, '2015-07-01'),
('D', 'DD', 9, '2016-10-01'),
('E', 'EE', 9, '2014-10-25')
";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
/// Hakan SONMEZ solution
$sql3 = mysqli_query($conn, "
DELETE tbl1 FROM $table tbl1, $table tbl2 WHERE tbl1.date < tbl2.date AND tb1.value = tb2.value
");
?>
答案 0 :(得分:1)
DELETE tbl1 FROM new_table tbl1, new_table tbl2 WHERE tbl1.date < tbl2.date AND tbl1.value = tbl2.value;
编辑:在尝试之前复制数据。
答案 1 :(得分:0)
这些方面的内容应该有效:
delete t from table t
join (select value, max(Date) maxdate, from table group by value) as t1
on t.value=t1.value
where date<maxdate