Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting the nth row mysql

I'm using MySQL v5.0.45 and trying to delete the nth row in a table irrespective of its ID number. I set up a prototype in PHP before integrating it into my web development project where I set up the following in my database:

CREATE TABLE prototype_1 (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name varchar(30));

INSERT INTO prototype_1 (name) VALUES ('A');
INSERT INTO prototype_1 (name) VALUES ('B');
INSERT INTO prototype_1 (name) VALUES ('C');

Simple enough! Now I tried using 'LIMIT' but I get the following error:

"ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'"

Now I understand you cannot use LIMIT in subqueries, however, is there not some sort of work around?

I can select the nth row and display it nicely with the following:

SELECT * FROM prototype_1 LIMIT 1,1;

Thus returning 'B' but why cannot I delete!?

like image 541
Riyan Avatar asked Mar 03 '11 16:03

Riyan


1 Answers

You need a little trick like this

delete from prototype_1 where id = (select id from (select id from prototype_1 order by id limit 1,1) as t)

From docs

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants

(...)

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

like image 96
Nicola Cossu Avatar answered Sep 30 '22 15:09

Nicola Cossu