search

Home  >  Q&A  >  body text

Delete from two tables in one query

<p>I have two tables in MySQL</p> <pre class="brush:php;toolbar:false;">#messages table : messageid messagetitle . . #usersmessages table usersmessageid messageid userid . .</pre> <p>Now if I want to delete from the message table I can. But when I delete the message by messageid, the record still exists on usersmessage and I have to delete from both tables immediately. </p> <p>I used the following query: </p> <pre class="brush:php;toolbar:false;">DELETE FROM messages LEFT JOIN usersmessages USING(messageid) WHERE messageid='1' ;</pre> <p>Then I test</p> <pre class="brush:php;toolbar:false;">DELETE FROM messages , usersmessages WHERE messages.messageid = usersmessages.messageid and messageid='1' ;</pre> <p>But these two queries did not complete the task. </p>
P粉401901266P粉401901266453 days ago486

reply all(2)I'll reply

  • P粉164942791

    P粉1649427912023-08-28 10:18:24

    DELETE a.*, b.* 
    FROM messages a 
    LEFT JOIN usersmessages b 
    ON b.messageid = a.messageid 
    WHERE a.messageid = 1

    Translation: Delete from table messages, where messageid = 1, if table uersmessages has messageid = messageid of table messages, then delete the rowUser message table.

    reply
    0
  • P粉595605759

    P粉5956057592023-08-28 09:11:20

    Can't they be separated by semicolons?

    Delete from messages where messageid = '1';
    Delete from usersmessages where messageid = '1'

    or

    Just use INNER JOIN as shown below

    DELETE messages , usersmessages  FROM messages  INNER JOIN usersmessages  
    WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1'

    reply
    0
  • Cancelreply