简体   繁体   中英

How to find a parent with a child excluding another in mysql?

在此处输入图片说明 An item has many tags through the taggables table. In MYSQL, how do I search for items tagged as "Blue" that aren't also tagged as "Square"?

You can solve this using a subquery that returns the ids of the records you want to commit:

select i.*
from items as i
left join (
    select distinct tg.item_id
    from taggables as tg
    inner join tags as t on tg.tag_id = t.id
    where t.name = 'square'
    ) as a on I.id = a.item_Id
where a.item_id is null and i.name = 'blue';

You can do this with EXISTS and NOT EXISTS :

SELECT items.* FROM items
WHERE EXISTS(
    SELECT * FROM item_has_tags
        WHERE item_id=items.id AND name='square')
AND NOT EXISTS(
    SELECT * FROM item_has_tags
        WHERE item_id=items.id AND name='blue');

To simplify things a bit you can create a view

CREATE VIEW item_has_tags AS
     SELECT * FROM taggables 
          JOIN tags ON (taggables.tag_id = tags.id);

and the query then becomes,

SELECT items.* FROM items WHERE
    EXISTS(SELECT * FROM item_has_tags WHERE item_id=items.id AND name='square')
AND NOT
    EXISTS (SELECT * FROM item_has_tags WHERE item_id=items.id AND name='blue');

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