我在 MySql 中有一个用户表,如果下一行具有相同的 first_name,我需要编写将删除行的查询。
问问题
122 次
1 回答
0
假设您有这样的表,并且您想删除第二条记录,因为第二条和第三条记录的名称相同。(基兰)
+-----+-----------+-------------+------------+---------------------------+
| ID | Name | DoB | Address | Email |
+-----+-----------+-------------+------------+---------------------------+
| 1 | Ramesh | 1990-12-30 | Indore | Ramesh@gmail.com |
| 2 | Khilan | 1990-12-12 | Ottawa | Khilan@gmail.com | > Name: Khilan
| 3 | Khilan | 1992-02-02 | New York | KhilanNY@gmail.com | > Name: Khilan
| 4 | Miriam | 1990-05-12 | Milwaukee | MiriamRSeyler@armyspy.com |
| 5 | Mary | 1993-12-23 | Milwaukee | dee.robel1976@hotmail.com |
| 6 | Elaine | 1980-01-20 | Memphis | kimberly2004@yahoo.com |
| 7 | Margaret | 1992-02-12 | Minnesota | concepcjaskols@yahoo.com |
| 8 | Khilan | 1992-03-14 | New York | KhilanNY@gmail.com |
+-----+-----------+-------------+------------+---------------------------+
PRIMARY KEY: ID
然后你可以使用这个查询来做到这一点。
DELETE FROM TableName
WHERE id IN (SELECT id
FROM (SELECT t1.id AS id
FROM TableName t1
LEFT JOIN TableName t2
ON t1.id = t2.id - 1
WHERE t1.name = t2.name) tmp)
如果 ID 序列中存在间隙,请改用此查询。
DELETE FROM person
WHERE id IN (SELECT id
FROM (SELECT t1.id
FROM (SELECT *,
Row_number() OVER (ORDER BY id) AS RN
FROM person) t1
LEFT JOIN (SELECT *,
Row_number() OVER (ORDER BY id) AS RN
FROM person) t2
ON t1.rn = t2.rn - 1
WHERE t1.NAME = t2.NAME
ORDER BY t1.id) tmp)
删除后的输出 ( SELECT * FROM TableName
)
+-----+-----------+-------------+------------+---------------------------+
| ID | Name | DoB | Address | Email |
+-----+-----------+-------------+------------+---------------------------+
| 1 | Ramesh | 1990-12-30 | Indore | Ramesh@gmail.com |
| 3 | Khilan | 1992-02-02 | New York | KhilanNY@gmail.com |
| 4 | Miriam | 1990-05-12 | Milwaukee | MiriamRSeyler@armyspy.com |
| 5 | Mary | 1993-12-23 | Milwaukee | dee.robel1976@hotmail.com |
| 6 | Elaine | 1980-01-20 | Memphis | kimberly2004@yahoo.com |
| 7 | Margaret | 1992-02-12 | Minnesota | concepcjaskols@yahoo.com |
| 8 | Khilan | 1992-03-14 | New York | KhilanNY@gmail.com |
+-----+-----------+-------------+------------+---------------------------+
在线演示:https ://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6510a3a610e83d27a8d4dc43aeeb3be7
于 2019-04-13T04:47:26.287 回答