我想通过删除表中的重复项来清理我的表,但保留最新版本的重复记录。
我的表与下面的表类似。我想删除flightNo“AF 8253”复制品,但请将航班号“AF 8253”与抵达时间保留在14:20。
id depOrArriv flightNo airline dest origin depature arrivalTime status
183 Arrival AF 8253 AirUganda NULL Nairobi NULL 14:05 Scheduled
184 Arrival AF 8253 AirUganda NULL Nairobi NULL 14:20 Scheduled
185 Arrival SCAN09 SCAN Air NULL Kampala NULL 10:30 Scheduled
我已尝试过以下代码,但似乎无法正常工作。
$sql = "CREATE TEMPORARY TABLE schedule_temp AS
SELECT DISTINCT * FROM sortedArrivals
DELETE FROM sortedArrivals
INSERT INTO sortedArrivals(
timePeriod, depOrArriv, flightNo, airline, dest,
origin, depature, don, arrivalTime, status)
SELECT timePeriod, depOrArriv, flightNo, airline,
dest, origin, depature, don, arrivalTime, status
FROM schedule_temp";
if (!$mysqli->query($sql))
{
die('Error: ' . $mysqli->error);
}
有人可以帮我指点正确的方向吗? 期待收到你的回复。
答案 0 :(得分:1)
您可以尝试使用此功能,假设重新安排的航班的 RowID 比前一个更高,并且您可以通过使用相同的 flightNo 来识别副本,< strong>航空公司和来源(在其他情况下,您还可以向GROUP BY子句添加更多变量):
DELETE FROM sortedArrivals
WHERE RowId NOT IN
(SELECT MAX(RowId) FROM sortedArrivals GROUP BY flightNo, airline, origin);
答案 1 :(得分:1)
这是一个SQL小提琴: http://sqlfiddle.com/#!2/a7e36/1
create table flight (id varchar(100), arrivalTime varchar(100));
insert into flight values ('8253','14:05');
insert into flight values ('8253','14:20');
insert into flight values ('8254','15:05');
insert into flight values ('8254','15:20');
DELETE FROM flight
WHERE not exists (
SELECT * FROM
(SELECT f2.ID
, MAX(f2.arrivalTime) arrivalTime
FROM flight f2
GROUP BY f2.ID) x
WHERE x.ID = flight.ID and x.arrivalTime = flight.arrivalTime
);
SELECT * from flight;
输出:
ID ARRIVALTIME
8253 14:20
8254 15:20
答案 2 :(得分:0)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(flightNo VARCHAR(12) NOT NULL
,arrivalTime TIME NOT NULL
,PRIMARY KEY (flightno,arrivaltime)
);
INSERT INTO my_table VALUES
('AF 8253','14:05'),
('AF 8253','14:20'),
('SCAN09','10:30');
SELECT * FROM my_table;
+----------+-------------+
| flightNo | arrivalTime |
+----------+-------------+
| AF 8253 | 14:05:00 |
| AF 8253 | 14:20:00 |
| SCAN09 | 10:30:00 |
+----------+-------------+
DELETE a
FROM my_table a
LEFT
JOIN
( SELECT x.*
FROM my_table x
JOIN
( SELECT flightno
, MAX(arrivaltime) max_arrivaltime
FROM my_table
GROUP BY flightno
) y
ON y.flightno = x.flightno
AND y.max_arrivaltime = x.arrivaltime
) b
ON b.flightno = a.flightno
AND b.arrivaltime = a.arrivaltime
WHERE b.flightno IS NULL;
SELECT * FROM my_table;
+----------+-------------+
| flightNo | arrivalTime |
+----------+-------------+
| AF 8253 | 14:20:00 |
| SCAN09 | 10:30:00 |
+----------+-------------+