search

Home  >  Q&A  >  body text

Unable to use LIMIT delete in mysql join query between multiple tables

This is my SQL query:

DELETE gur
FROM group_master gm
JOIN group_users gu
ON gu.group_id=gm.id
JOIN group_user_roles gur
ON gur.group_user_id=gu.id
WHERE gm.school_code = 14741359 AND gm.ayid=3
LIMIT 1;

I get an error saying there is a syntax error near LIMIT. I found a solution here: DELETE using LEFT JOIN with LIMIT in MySQL. I can't convert the query into a select statement.

P粉180844619P粉180844619233 days ago458

reply all(1)I'll reply

  • P粉166675898

    P粉1666758982024-04-02 00:49:42

    Only single tableDELETE supports LIMIT. < /p>

    Use the query as a SELECT with LIMIT and get the ID of the row (remember - LIMIT without ORDER BY is a lottery). Then delete the corresponding rows from the other copy of the table.

    DELETE group_user_roles 
    FROM group_user_roles 
    JOIN (SELECT gur.id
          FROM group_master gm
          JOIN group_users gu ON gu.group_id=gm.id
          JOIN group_user_roles gur ON gur.group_user_id=gu.id
          WHERE gm.school_code = 14741359 AND gm.ayid=3
          /* ORDER BY ??? */ LIMIT 1
          ) USING (id)
    

    Replace id with the primary key or unique column/expression of the group_user_roles table.

    reply
    0
  • Cancelreply