Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 选择联接表中字段在每行中相同的行_Mysql_Sql - Fatal编程技术网

Mysql 选择联接表中字段在每行中相同的行

Mysql 选择联接表中字段在每行中相同的行,mysql,sql,Mysql,Sql,假设我有以下表格: 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

假设我有以下表格:

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);
我需要一个将返回的查询:

Parents
+------------+
|    id      |
+------------+
|     1      |
|     3      |
+------------+
其中
id
是父项id。结果表仅包含始终(任何一天)
true
的父项。请注意,没有子女的父母应被排除在外

我的尝试:

SELECT id
FROM parents p
INNER JOIN children c ON c.parent_id=p.id
WHERE c.status = TRUE
GROUP BY id
但它也将为父级提供
id=2

另一次尝试:

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

但这种方法也将包括id=5的父项,必须将其排除在外。

您不需要加入父项

SELECT parent_id
FROM children
GROUP BY parent_id
HAVING MIN(Status) = 'TRUE'
   AND MAX(Status) = 'TRUE'
除了TRUE之外,没有其他状态。

这也可能有效

SELECT DISTINCT p.id
  FROM parents p
 WHERE p.id IN ( 
                 SELECT c.parent_id
                   FROM children c
                  WHERE c.status = TRUE
                    AND c.parent_id = p.id 
               )

使用
位添加

select a.id
from parents a
join children b on a.id = b.parent_id
group by a.id
having bit_and(b.status);


这将为您提供所需的结果。

如果
status
可能为
NULL
,您可以添加
和COUNT(*)=COUNT(status)
。谢谢!这是在所有情况下给出正确答案的唯一答案,也是最直接的答案。
SELECT id FROM parent P 
WHERE (P.id) IN
(SELECT c.parent_id FROM children c WHERE c.status = TRUE)