Search code examples
mysqlselectwhere-in

Append wildcards in SELECT with MySQL


Using MySQL:

I have a table 'city': id, 'name', 'serving' contains:

'1', 'Athens', 'Athens, Etowah, Madisonville'
'2', 'Etowah', 'Etowah, Athens, Madisonville, Niota'
'3', 'Madisonville', 'Madisonville, Niota, Athens, Etowah'
'4', 'Soddy Daisy', 'Soddy Daisy, Decatur, Graysville'
'5', 'Signal Mountain', 'Signal Mountain, Walden, Jasper, Kimball'

I have a table 'zipcodes': id, 'zipcode', 'cityname' contains:

'1','00000','Athens'
'2', '00001', 'Dayton'
'3', '00002', 'Soddy Daisy'

So in city, 'serving' is a comma-delimited string of areas surrounding a major city 'name' starting with the major city.

I can get a list from my database using this statement:

SELECT serving FROM `city` WHERE serving LIKE '%Athens%'

What I am trying to get is the major city 'name' from the 'city' list where the 'cityname' is NOT in serving. Major bonus if it returned a list where the 'cityname' is prioritized by position in the string. The goal initially is to make sure I have every 'cityname' in zipcodes covered in the 'serving' field of city.

Desired output Example '00001' Dayton - (NOT IN serving): Dayton

Bonus; Then when finding '00000' Athens (IN serving): Athens, Etowah, Madisonville

I have tried:

SELECT z.cityname FROM zipcodes z
WHERE z.cityname NOT IN (
    SELECT c.serving FROM city c
        WHERE c.serving LIKE CONCAT('''%',z.cityname,'%'''))

But this isn't finding any matches in the city 'serving' list.

I tried formatting the string differently but I am getting errors.

SELECT z.cityname FROM zipcodes z
WHERE z.cityname NOT IN (
    SELECT c.serving FROM city c
        WHERE c.serving LIKE '%' + z.cityname + '%')

So I am figuring it is in my string for the wildcard match is where this is failing. So any advice would be greatly appreciated.

My database experience is mostly MSSQL and searching here and google is not rendering what I am looking for as to why my SELECT isn't working.

Thank you!

Edit: added more samples for the datatables


Solution

  • if you wanted to find zip codes that are not "served" by any of the cities you can use:

    SELECT z.zipcode, z.cityname 
    FROM zipcodes z
    WHERE NOT EXISTS (
      SELECT * 
      FROM city c
      WHERE c.serving LIKE CONCAT('%',z.cityname,'%')
    )
    

    See db-fiddle.