This is my DB schema
Table_A
-id
-status
Table_B
-id
Table_A_has_B
-id
-id_A
-id_B
I need to select all records from Table_B, where all associated Table_A records has status=1
and if a Table_B record hasn't any associated Table_A also should be selected.
Test case:
CREATE TABLE table_a (id int(2),status int(1));
INSERT INTO table_a (id, status)
VALUES (1,1),(2,0),(3,1),(4,1),(5,1);
CREATE TABLE table_b (id int(2));
INSERT INTO table_b (id) VALUES (1),(2),(3),(4);
CREATE TABLE table_a_has_b (id int(2),id_A int(2),id_B int(2));
INSERT INTO table_a_has_b (id, id_A, id_B)
VALUES(1, 1, 1),(2, 2, 1),(3, 3, 1),(4, 4, 2),(5, 5, 2),(6, 3, 4),(7, 4, 4);
The query should select:
+----+
|b.id|
+----+
| 2|
| 3|
| 4|
+----+
- Id 1 shouldn't be selected because one of its table_a records has status=0
- Id 2 and 4 are should be selected because all its table_a records has status=1
- Id 3 should be selected because don't has table_a records associated, another point of view for the same criterion is: Id 3 should be selected because don't have any table_a records where status=0