Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows where field in joining table is same in every row

Tags:

sql

mysql

Suppose I have the following tables:

CREATE TABLE parents (
    id int primary key
);

CREATE TABLE children (
    parent_id int,  --id from parents
    day int,
    status bool,
}

INSERT INTO parents (id) VALUES (1);
INSERT INTO children (parent_id, day, status) VALUES (1, 1, TRUE);
INSERT INTO children (parent_id, day, status) VALUES (1, 2, TRUE);

INSERT INTO parents (id) VALUES (2);
INSERT INTO children (parent_id, day, status) VALUES (2, 1, TRUE);
INSERT INTO children (parent_id, day, status) VALUES (2, 2, FALSE);

INSERT INTO parents (id) VALUES (3);
INSERT INTO children (parent_id, day, status) VALUES (3, 1, TRUE); 

INSERT INTO parents (id) VALUES (4);
INSERT INTO children (parent_id, day, status) VALUES (4, 1, FALSE);

INSERT INTO parents (id) VALUES (5);

I need a query that will return:

Parents
+------------+
|    id      |
+------------+
|     1      |
|     3      |
+------------+

where id is parents id. The resulting table only contains the parents that always(any day) true. Note that parents without children should be excluded.

My attempt:

SELECT id
FROM parents p
INNER JOIN children c ON c.parent_id=p.id
WHERE c.status = TRUE
GROUP BY id

But it will also give parent with id=2.

Another attempt:

SELECT id
FROM parents p
LEFT OUTER JOIN children c ON c.parent_id=p.id AND c.status=FALSE
WHERE c.status IS NULL
GROUP BY id

But this approach will also include parent with id=5, which must be excluded.

like image 351
nickbusted Avatar asked Jan 09 '16 19:01

nickbusted


People also ask

Which join returns rows when there is a match in both tables?

INNER JOIN TABLE2 When the Join condition is met, it returns matched rows in both tables with the selected columns in the SELECT clause.

Which join returns all matched or unmatched rows?

Outer joins are joins that return matched values and unmatched values from either or both tables.

Which type of join is used to returns all rows if there is one match in both tables Mcq?

SQL outer join On joining tables with a SQL inner join, the output returns only matching rows from both the tables.

Which join returns rows when there is at least one matching row between the tables?

Introduction to SQL LEFT JOIN clause In the previous tutorial, you learned about the inner join that returns rows if there is, at least, one row in both tables that matches the join condition. The inner join clause eliminates the rows that do not match with a row of the other table.


1 Answers

You don't need to join to parents.

SELECT parent_id
FROM children
GROUP BY parent_id
HAVING MIN(Status) = 'TRUE'
   AND MAX(Status) = 'TRUE'

No other Status besides TRUE.

like image 83
dnoeth Avatar answered Oct 01 '22 10:10

dnoeth