2014-02-08 121 views
0

我有一些產品的數據庫,他們可以用許多類別「標記」。有些產品沒有分配類別,我需要找到它們。需要查找沒有分類的記錄。我創造了這個表:在多對多關係中選擇沒有類別的記錄

ITEMS

+----+------+ 
| 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; 

回答

1

您可以使用子查詢使用NOT IN子句

SELECT i.id 
FROM item i 
WHERE i.id NOT IN (SELECT r.id_item 
    FROM RELATIONSHIP r); 
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; 
相關問題