简体   繁体   中英

Delete rows where id is same as in other table

Ok, here's the deal: I have following two tables in MySql-database:

**custwishes**
userid
wishid

**coursewishes**
wishid
coursename
wishmonth

"custwishes.userid" references to users-table, and custwishes.wishid is same as "coursewishes.wishid".

Now I would like to delete all records from coursewishes, where coursewishes.wishid=custwishes.wishid AND custwishes.userid=?.

I can do this with php, collecting all the necessary id's and making the delete-query in a loop for those id's, but that doesn't seem like a good idea.

I didn't even know what kind of title I should put for this question, so I hope it's not too misleading.

Any help would appreciated!

Update 07082014:13:28

I tried the "Ende Neu"'s method, but no luck. The suggestion deletes from custwishes, not from coursewishes like I would like it to do. I tried this modified version:

    DELETE
    FROM coursewishes
    WHERE coursewishes.wishid 
    IN (
      SELECT wishid 
      FROM custwishes
    )
    AND custwishes.userid = 5

This obviously results in error, because system cannot find custwishes.userid.

Perhaps there is a way to use JOIN or something alike? I'll have it a go and post what happens.

Update 11082014:12:01

Returned to the problem today, and I managed to get the cascading to work. Problem was, that I had the cascade made wrong way. :) Meaning that it cascaded from coursewishes to custwishes, not the other way around like it was supposed to.

You can use JOIN in DELETE statement.

If you only want to delete from coursewishes, use this statement

DELETE coursewishes
FROM coursewishes
JOIN custwishes ON coursewishes.wishid = custwishes.wishid 
WHERE custwishes.userid = 5;

If you want to delete from both tables, use

DELETE coursewishes, custwishes
FROM coursewishes
JOIN custwishes ON coursewishes.wishid = custwishes.wishid 
WHERE custwishes.userid = 5;

ON DELETE cascade works in one direction only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM