简体   繁体   中英

Delete from table B where column value like table a with wildcards

So I have two tables

seeds
- id
- domain

subdomain
- id 
- domain
- ip

I want to filter the subdomains against the domains

for example

seeds
Id  Domain
0   google.com
1   test.com

subdomain
Id   domain          ip
0    test.google.com    null
1    api.google.com     null
2    dnr.com            null
3    neverssl.com       null

I'm trying to write a single query that deletes the rows in subdomain that don't contain a domain from seeds

What have you tried?

delete subdomain 
where id not in 
(select subs.id from seed as seeds 
join 
subdomain as subs on subs.domain 
like concat('%', seeds.domain));

and

delete subdomain 
where id not in
(SELECT sd.id
FROM subdomain sd
LEFT JOIN seed s
  ON sd.domain LIKE CONCAT('%', s.Domain)
WHERE s.id IS NULL)

both of these queries just delete all of the rows

You can use not exists :

delete from subdomain
where not exists (
    select 1
    from seeds s
    where subdomain.domain like concat('%', s.domain)
)

DEMO

Use the LEFT JOIN + NULL pattern to find rows that don't match.

DELETE d
FROM subdomain AS d
LEFT JOIN seeds AS s ON d.domain LIKE CONCAT('%', s.domain)
WHERE s.id IS NULL

DEMO

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