在多对多关系中选择没有类别的记录

时间:2014-02-08 13:17:44

标签: php mysql sql

我有一些带有一些产品的数据库,它们可以被许多类别“标记”。有些产品没有指定类别,我需要找到它们。无法找到没有类别的记录。我创建了这个表:

+----+------+
| ID | Item |
+----+------+
|  1 | qwe  |
|  2 | asw  |
|  3 | wgr  |
+----+------+

分类

+----+----------+
| ID | Category |
+----+----------+
|  1 | xxx      |
|  2 | yyy      |
+----+----------+

关系

+---------+--------+
| id_item | id_cat |
+---------+--------+
|       1 |      1 |
|       1 |      2 |
|       2 |      1 |
+---------+--------+

这是(不工作)查询:

SELECT item.id COUNT(relationship.id_item) AS n
FROM item
JOIN relationships GROUP
BY relationships .n
WHERE item.id = relationships.id_item
AND relationships.n =0;

2 个答案:

答案 0 :(得分:1)

您想要一个左连接,然后找到那些不匹配的连接:

SELECT i.id, COUNT(relationship.id_item) AS n
FROM item i LEFT OUTER JOIN
     relationships r
     on i.id = r.id_item
WHERE r.id_item is null;

答案 1 :(得分:1)

您可以将子查询与NOT IN子句

一起使用
SELECT i.id
FROM item i
WHERE i.id NOT IN ( SELECT r.id_item
    FROM RELATIONSHIP r);