2

、のitem_category2 つの列を持つテーブルがあります。アイテムとカテゴリは、多対多の関係です。item_idcat_id

私のテーブルがこのように見える場合...

item_id | cat_id
1       | 1
1       | 2
2       | 3
2       | 4
3       | 5
3       | 6
4       | 7
4       | 8
5       | 9
5       | 10

... 2 または 7 (2、3、5 の s を生成)である行item_idを持たない s の個別のリストを選択するにはどうすればよいですか?category_iditem_id

4

6 に答える 6

5

集計とhaving句を使用してこれを行います。

select item_id
from item_category ic
group by item_id
having max(cat_id = 2) = 0 and
       max(cat_id = 7) = 0

これは、「set-within-sets」クエリの例です。group bywithの使用havingは、このようなクエリの最も一般化可能な形式です。たとえば、カテゴリ 3 が含まれていることを確認したい場合は、having句を次のように変更します。

having max(cat_id = 2) = 0 and
       max(cat_id = 7) = 0 and
       max(cat_id = 3) = 1
于 2013-07-18T02:09:10.240 に答える
2

ネストされた を使用しますが、おそらくself joinSELECTでこれを行う方法があります。

select item_id 
from item_category t
where not exists (
    select 1 
    from item_category 
    where item_id = t.item_id 
        and cat_id in (2,7)
)
group by item_id;

NOT IN代わりに句を使用することもできます。

SELECT DISTINCT item_id 
FROM item_category
WHERE item_id NOT IN (
    select distinct item_id 
    from item_category 
    where cat_id in (2,7));

両方のクエリのパフォーマンスはおそらく似ていますが、データ セットが大きいかどうかをテストできます。

于 2013-07-18T01:24:10.907 に答える
0

これは、単純なサブクエリで実行できます。

SELECT DISTINCT item_id
FROM ic
WHERE item_id NOT IN (
  SELECT DISTINCT item_id FROM ic WHERE cat_id IN (2,7)
 );
于 2013-07-18T01:43:24.173 に答える