0

私は属性という名前のテーブルを持っています:

id attributeid type
1         8      2
2         8      1
3         4      1

では、2 と 1 の両方のタイプを持つ attributeid を選択するにはどうすればよいでしょうか。この場合、属性 8 のみが修飾されます。

select attributeid 
from attribute
where type in (1,2)

これは、間違っている 4,8 を返すため、私が望む結果を生成しません。

ありがとう。

4

6 に答える 6

5

次のようなものを使用できます。

select t1.attributeid
from yourtable t1
where type = 1 
  and exists (select type
              from yourtable t2
              where t1.attributeid = t2.attributeid
                and t2.type = 2)

デモで SQL Fiddle を参照してください

于 2012-09-17T10:22:01.097 に答える
3

type同じに対して同じ値を持つ複数の行が存在できない場合、次のattributeidようなものが適切だと思います。

select attributeid
from attribute
where type in (1,2)
group by attributeid
having COUNT(*) = 2

GROUP BYこれは、( andなしの) クエリHAVINGが同じ に対して 2 つの行を生成したかどうかを効果的に尋ねていますattributeid。別の型の値を追加すると、これは簡単に拡張できます。

select attributeid
from attribute
where type in (1,2,6)
group by attributeid
having COUNT(*) = 3

そして、一般的に関係分割と呼ばれます。

于 2012-09-17T10:33:06.237 に答える
1

将来、次のような行が表示される可能性があります。

id attributeid type
1         8      3
1         8      4

次に、この条件も満たすようにクエリを再度変更しますか??? お気に入り

where type in(1,2,3,4)

ユニバーサルクエリにするには、試すことができます

select attributeid 
from attribute
where type in (select unique(type) from attribute)
group by attributeid 
having COUNT(*) = (select count(unique(type)) from attribute);
于 2012-09-18T08:38:45.807 に答える
0

あなたはで試すことができます

SELECT A.attributeid
FROM Table A
WHERE type = 1 
AND EXISTS (SELECT  type FROM Table B WHERE A.attributeid = B.attributeid AND B.type = 2)
于 2012-09-17T10:32:47.850 に答える
0

テーブルの名前がattributeの場合、各属性は 1 回だけ出現する必要があります。名前などを付けるべきではありませんattributetypeか?

ともかく:

select 
  * 
from 
  Attribute t
where
  exists (
    select * from Attribute t1 
    where t1.AttributeId = t.AttributeId and t1.Type = 1) and
  exists (
    select * from Attribute t1 
    where t1.AttributeId = t.AttributeId and t1.Type = 2)
于 2012-09-17T10:21:54.197 に答える
-2

多分もっと似たものはどうですか:

(タイプ = 1) および (タイプ = 2) の属性から属性 ID を選択します。

于 2012-09-17T10:21:54.587 に答える