Search code examples
mysqlselectsql-like

NOT LIKE MySQL statement


I have an issue with NOT LIKE statement. I have two sql tables setup as tag map. First table finds tag_id according to the search name and second finds resource_id based on tag_id found. When I run a NOT LIKE statement below, I receive the result: resource_id = 1.

Tag map tables

tag_id name
1      meat
2      vegetarian

resource_id tag_id
1           1
1           2

Query

SELECT 
    f.id, f.food_name, tm.resource_id, tm.tag_id, t.name 
FROM 
    tag as t, tagmap as tm JOIN item as f ON 
    (
        f.id = tm.resource_id AND tm.tag_id IN 
        (
        SELECT 
            t.tag_id 
        FROM 
            tag as t 
        WHERE 
            t.name NOT LIKE '%meat%' 
        ) 
     )
GROUP by f.id

All I need this query to do is, if it finds a resource_id with tag name "meat" I don't want it to return this resource_id.

If my explanation is not clear please let me know.


Solution

  • Then you must search for:

    select resource_id
    from tagmap
    where resource_id not in (select resource_id
                              from tagmap
                              where tag_id in (select tag_id from tag
                                               where name like '%meat%'));
    

    or with a join:

    select *
    from tagmap
    where resource_id not in (select m.resource_id
                              from tagmap m, tag t
                              where m.tag_id = t.tag_id and t.name like '%meat%');
    

    You look for resource_id with name "meat" and exclude these not in in your select.

    This might correspond to your query, but I'm not really sure:

    select f.id, f.food_name, tm.resource_id, tm.tag_id, t.name 
    from tag as t, tagmap as tm, item as f
    where f.id = tm.resource_id
          and tm.tag_id = t.tag_id
          and tm.resource_id not in (select m.resource_id
                                     from tagmap m, tag t
                                     where m.tag_id = t.tag_id
                                           and t.name like '%meat%')
    group by f.id;