Search code examples
mysqlsqlsubqueryleft-joinsql-delete

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


Solution

  • You can use not exists:

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

    DEMO