2016-12-13 4 views
0

条件が厳密に満たされるように行を選択するクエリを作成しようとしています。私がしようとしていることを示す最良の方法は、一例です。MySQL "のみ"条件を使用して行を選択します。

は、私は私が望む何を次の表に

+------------+ 
| A_Table | 
+----+-------+ 
| id | value | 
+----+-------+ 
| 1 |  1 | 
| 2 |  1 | 
| 2 |  2 | 
| 3 |  1 | 
| 3 |  2 | 
| 3 |  5 | 
+----+-------+ 

があるとだけ与えられた値と一致したIDを返すクエリです。たとえば、厳密に(1,2)の値を持つidを必要としているとしたら、id = 2がこれを満たす唯一のものです。 id = 3は値1と2を持っていますが、厳密にそれらの値(id = 1だけでなく)も持っていません。

ここに私が思い付いたクエリが

select id 
from A_Table a 
where value in (1,2) 
and not exists (
    select b.id 
    from A_Table b 
    where value not in (1,2) 
    and b.id = a.id 
); 

である。しかしオペレータで、私は方法がわからないんだけど、ID 1のためだけの値が1に満足しているので、これは、1と2の両方を返しています「厳密な」部分を強制する。

答えて

1

私はこの使用して集約するだろう:あなたがここにgroup by

select id 
from tbl1 
group by id 
having count(distinct value) = 2; 

などを使用することができます

select a.id 
from a_table a 
group by a.id 
having sum(a.value = 1) > 0 and   -- id has value = 1 
     sum(a.value = 2) > 0 and   -- id has value = 2 
     sum(a.value not in (1, 2)) = 0; -- id has nothing else 
+0

彼y @ゴードン、素晴らしいもの!私はhave節の中で列比較を使うこの方法についてまだ学んでいない。あなたはむしろsumの代わりにcountを使用しますが、負の値は許されますか? – Anand

+1

ブール式を合計しているため、1または0だけが合計されるため、ネガティブではありません。 (編集:カウントで試したところ、うまくいかなかった)。 – McAngus

0

私の提案:

select id 
from A_table as a 
where exists (
    select 1 
    from A_Table 
    where value in (1, 2) 
    and id = a.id 
    ) 
and not exists (
    select 1 
    from A_Table 
    where value not in (1, 2) 
    and id = a.id 
    ) 
group by id 
関連する問題