简体   繁体   中英

MySQL: Deleting rows that don't have a match in another table

I have 3 tables: links, keywords, and keywords_links. keywords_links joins the two other tables. Right now I'm trying to write a PHP function that deletes a link. It would also have to delete all the keywords that are only used by the link that will be deleted. I'm stuck at the MySQL query to delete those keywords.

Here's what I have right now:

DELETE FROM keywords INNER JOIN keywords_links ON keywords_links.keyword_id=keywords.id WHERE keywords_links.link_id='123' AND NOT EXISTS(...?)

Edit: This seems to be working, is there a more efficient way? (with no subqueries?)

DELETE
FROM keywords
INNER JOIN keywords_links ON keywords_links.keyword_id = keywords.id
WHERE keywords_links.link_id = '123'
AND ! 
EXISTS (
  SELECT * 
  FROM keywords_links
  WHERE keyword_id = keywords.id
  AND link_id != '123'
)

Try to separate the sqls (1 for table), delete the link, delete all the keywords_links of that link and delete all keywords NOT IN (or NOT EXISTS ) keywords_links table.

In that way you can delete all keywords which are only used by this link (if a keyword is user in other link will be in keywords_links and it don't be deleted).

Or you can do two Triggers: on delete in links and on delete in keywords_links

Instead of an INNER JOIN , you need a LEFT JOIN and look for NULLs in the related table links . Please test this first with a SELECT instead of DELETE FROM .

DELETE FROM
  keywords
  LEFT JOIN keywords_links ON keywords.id = keywords_links.keyword_id
  LEFT JOIN links ON keywords_links.link_id = links.id
WHERE 
  keywords_links.link_id=123
  AND links.id IS NULL

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