简体   繁体   中英

Mysql delete 5th element of a table

I have a table:

 ID Friend
John    Rita
John    Jack
Jack    Rita
Rita    John
John    Peter
John    Owen
John    Eric
John    Louis

I want to write a query where I delete all ID 's after the 5th element. In other words I want to keep for each ID maximum 5 friends .

I have tried with a group by or something like that, but I don't now exactly how I have to do the delete.

The result must be:

  ID    Friend
John    Rita
John    Jack
Jack    Rita
Rita    John
John    Peter
John    Owen
John    Eric

Short answer, no. The reason is that RDBMS's do not do not guarantee the order of entries .

If you need to be certain of the rows you are deleting, then you will need to know the order. I would recommend starting by adding an auto incrementing primary key column. From that, you will at least be certain of the order of entries. Eg:

ALTER TABLE table_name ADD column_name INT AUTO_INCREMENT PRIMARY KEY;

Note: This will only guarantee the order of future entries, not previously inserted entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM