找到没有关系的多对多
find many to many with no relation
我有一个 items
table、一个 tags
table 和一个 reletations
table。
我需要找到未标记的项目。
通过这个(有效的)查询,我找到了每个项目的标签编号:
SELECT i.id, i.text, COUNT( ti.item ) AS count
FROM items AS i
JOIN topic_item AS ti ON ti.item = i.id
GROUP BY ti.item
如果尝试修改查询:
ti.item != i.id
或者我添加
WHERE count = 0
但这不是正确的方法。
哪种方法正确?
尝试left join
如下
SELECT i.id, i.text, COUNT( ti.item ) AS count
FROM items AS i
LEFT JOIN topic_item AS ti ON ti.item = i.id
WHERE ti.item is null
GROUP BY ti.item
您可以使用 left join
,并获取没有匹配标签的项目:
SELECT i.id, i.text
FROM items AS i
LEFT JOIN topic_item AS ti ON ti.item = i.id
WHERE ti.item is null
您也可以使用 not exists
:
SELECT i.id, i.text
FROM items AS i
WHERE not exists(
select * from topic_item AS ti
where ti.item = i.id
)
我有一个 items
table、一个 tags
table 和一个 reletations
table。
我需要找到未标记的项目。
通过这个(有效的)查询,我找到了每个项目的标签编号:
SELECT i.id, i.text, COUNT( ti.item ) AS count
FROM items AS i
JOIN topic_item AS ti ON ti.item = i.id
GROUP BY ti.item
如果尝试修改查询:
ti.item != i.id
或者我添加
WHERE count = 0
但这不是正确的方法。 哪种方法正确?
尝试left join
如下
SELECT i.id, i.text, COUNT( ti.item ) AS count
FROM items AS i
LEFT JOIN topic_item AS ti ON ti.item = i.id
WHERE ti.item is null
GROUP BY ti.item
您可以使用 left join
,并获取没有匹配标签的项目:
SELECT i.id, i.text
FROM items AS i
LEFT JOIN topic_item AS ti ON ti.item = i.id
WHERE ti.item is null
您也可以使用 not exists
:
SELECT i.id, i.text
FROM items AS i
WHERE not exists(
select * from topic_item AS ti
where ti.item = i.id
)