SQLite return records that match a specifc set of records in another table
I have a table that has a one-to-many relationship to another table. I want the开发者_JS百科 records from the first table that match a specific set in the second table.
CREATE TABLE A (aId INTEGER PRIMARY KEY);
CREATE TABLE B (bId INTEGER PRIMARY KEY, aId INTEGER, c INTEGER);
INSERT INTO A (aId) VALUES (1);
INSERT INTO A (aId) VALUES (2);
INSERT INTO B (bId, aId, c) VALUES (1, 1, 1);
INSERT INTO B (bId, aId, c) VALUES (2, 1, 2);
INSERT INTO B (bId, aId, c) VALUES (3, 2, 2);
INSERT INTO B (bId, aId, c) VALUES (4, 2, 3);
For example, I was aId Where c is 1 and 2. so aId = 1. I don't want it to return aId 2 because while it matches c = 2 it doesn't have c = 1.
SELECT aId FROM B WHERE c IN(1,2);
Gives me 1,1,2. Is there something similar that matches all elements rather than any?
If you know how many items are in the IN clause for C,
SELECT aID FROM B WHERE C IN(1,2) GROUP BY aID HAVING COUNT(*)=2;
where the COUNT(*)
is equal to the number of elements in the IN
. If the filter is more complicated, we’ll need another approach.
精彩评论