Warm tip: This article is reproduced from serverfault.com, please click

MariaDB subquery use whole row

发布于 2020-11-30 15:24:17

Usually subqueries compare single or multiple fields and delete statements usually delete values by an ID. Unfortunately I don't have a ID field and I have to use an generic approach for differnt kind of tables. That's why I am working with a subquery using limit and offset as resolving rows.

I know that approach is risky, however is there any way to delete rows by subquerying and comparing the whole row?

DELETE FROM table WHERE * = ( SELECT * FROM table LIMIT 1 OFFSET 6 )

I am using the latest version of MariaDB

Questioner
marius
Viewed
0
dland 2021-01-14 21:49:37

This sounds like a really strange need, but who am I to judge? :)

I would simply rely on the primary key:

DELETE FROM table WHERE id_table = (SELECT id_table FROM table LIMIT 1 OFFSET 6)

update: oh, so you don't have a primary key? You can join on the whole row this way (assuming it has five columns named a, b, c, d, e):

DELETE t
FROM table t
INNER JOIN (
    SELECT a, b, c, d, e
    FROM table
    ORDER BY a, b, c, d, e
    LIMIT 1 OFFSET 6
) ROW6 USING (a, b, c, d, e);

Any subset of columns (e.g. a, c, d) that uniquely identify a row will do the trick (and is probably what you need as a primary key anyway).

Edit: Added an ORDER BY clause as per The Impaler's excellent advice. That's what you get for knocking an example up quickly.