I have some sample data, for example:
INSERT INTO mytable
([FK_ID], [TYPE_ID])
VALUES
(10, 1),
(11, 1), (11, 2),
(12, 1), (12, 2), (12, 3),
(14, 1), (14, 2), (14, 3), (14, 4),
(15, 1), (15, 2), (15, 4)
Now I'm trying to check if each group has an FK_ID
exact match of the TYPE_ID values ββfor 1, 2 & 3
.
So, the expected result is as follows:
(10, 1)
it will not work- As in the group
FK_ID = 10
, we have only one entry
(11, 1), (11, 2)
it should also fail- As in the group
FK_ID = 11
, we have two entries.
(12, 1), (12, 2), (12, 3)
it must pass- As in the group
FK_ID = 12
, we have two entries. - And everything
TYPE_ID
exactly matches the values 1, 2 & 3
.
(14, 1), (14, 2), (14, 3), (14, 4)
it should also fail(15, 1), (15, 2), (15, 4)
it should also fail- Despite the fact that we have three entries, this should fail, since
TYPE_ID
here (1, 2, 4) do not correspond to the required coincidence (1, 2, 3).
Here is my attempt:
select * from mytable t1
where exists (select COUNT(t2.TYPE_ID)
from mytable t2 where t2.FK_ID = t1.FK_ID
and t2.TYPE_ID IN (1, 2, 3)
group by t2.FK_ID having COUNT(t2.TYPE_ID) = 3);
, , FK_ID = 14
, .
: SQL Fiddle
, , , 4 TYPE_ID
, (1,2,3,4) (1,2,3,4,5), , .