一个项目通过taggables表有很多标签。在MYSQL中,如何搜索标记为" Blue"的项目。那些也没有被标记为" Square"?
答案 0 :(得分:0)
您可以使用子查询来解决此问题,该子查询返回您要提交的记录的ID:
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';
答案 1 :(得分:0)
您可以使用EXISTS
和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');
为了简化一些事情,你可以创建一个视图
CREATE VIEW item_has_tags AS
SELECT * FROM taggables
JOIN tags ON (taggables.tag_id = tags.id);
然后查询变为,
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');