[英]How to delete from my query where row_num > 2 in MySql?
I have this table in my database with the following schema:我的数据库中有这张表,其架构如下:
nearbystops(nearbystopname, latitude, longitude, mainaddress), I have done the following query nearstops(nearbystopname, latitude, longitude, mainaddress), 我做了如下查询
SELECT
nearbystopname,
latitude,
longitude,
mainaddress,
ROW_NUMBER() OVER (
PARTITION BY
nearbystopname,
mainaddress
ORDER BY
nearbystopname,
mainaddress
) row_num
FROM
DUSAgeocodeDB.nearbystops
which gives me the following:这给了我以下信息:
My question is, how would I go by deleting the results where row_num > 2 and reflecting the changes into my database?我的问题是,我将如何通过删除 row_num > 2 的结果并将更改反映到我的数据库中来 go ?
I have tried the following code:我尝试了以下代码:
with cte as (
SELECT
nearbystopname,
latitude,
longitude,
mainaddress,
ROW_NUMBER() OVER (
PARTITION BY
nearbystopname,
mainaddress
ORDER BY
nearbystopname,
mainaddress
) row_num
FROM
DUSAgeocodeDB.nearbystops
) delete from cte where row_num > 1;
but it gives me the following error:但它给了我以下错误:
Error Code: 1146. Table 'dusageocodedb.cte' doesn't exist
错误代码:1146。表 'dusageocodedb.cte' 不存在
Any help will be much appreciated!任何帮助都感激不尽!
Assuming you have a primary key on the table, then:假设您在表上有一个主键,那么:
delete ns
from DUSAgeocodeDB.nearbystops ns join
(select nearbystopname, mainaddress, min(id) as min_id
from DUSAgeocodeDB.nearbystops ns2
group by nearbystopname, mainaddress
) ns2
on ns2.nearbystopname = ns.nearbystopname and
ns2.mainaddress = ns.mainaddress and
ns.id > ns.id;
If you don't have a primary key, your best bet might be to repopulate the table:如果您没有主键,最好的办法可能是重新填充表:
create table temp_ns as
select nearbystopname, latitude, longitude, mainaddress,
row_number() over (partition by nearbystopname, mainaddress) as seqnum
from DUSAgeocodeDB.nearbystops ns;
truncate table DUSAgeocodeDB.nearbystops ns; -- SAVE first!!!
insert into DUSAgeocodeDB.nearbystops (nearbystopname, latitude, longitude, mainaddress)
select nearbystopname, latitude, longitude, mainaddress
from temp_ns
where seqnum = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.