Search code examples
mysqlsqlsql-delete

MySql Error - Delete Duplicates Rows with priority


Pre-Information

I've table called Test:

-- Table Creation
CREATE TABLE Test(
    id integer,
    title varchar (100)
);
-- Insertion
INSERT INTO Test Values 
    (1, "Hi"), 
    (2, 'Hello'), 
    (2, "Hellew"), 
    (3, "World"), 
    (3,"Wordy");

Test Table

| Id | title  |
|----|--------|
| 1  | Hi     |
| 2  | Hello  |
| 2  | Hellew |
| 3  | World  |
| 3  | Wordy  |

Process

I want to delete the duplicates id Based on the priority

The Problem

This is the output Error I get

ERROR 1093 (HY000) at line 5: You can't specify target table 'Test' for update in FROM clause

Required OUTPUT

| Id | title  |
|----|--------|
| 1  | Hi     |
| 2  | Hello  |
| 3  | World  |

Thanks,


Solution

  • You have not clearly mentioned what is the "priority" here. But looking at the output example, I am assuming that the priority is to keep those strings which are greater than the others with similar id. Here is my code:

        delete a.* from Test a join Test b
        on a.id = b.id where a.title < b.title;
        select * from Test;
    

    Reference

    MySQL: ALIASES