示例:
表A
id
1
2
3
表B
id value fk_a
1 -5 1
2 -7 1
3 5 2
4 -10 3
5 20 3
表A-> id 1的所有子表列(值)均为负数
答案 0 :(得分:1)
您可以使用ALL
PostgreSQL和Oracle的有效查询
select * from A
where id = ALL (select fk_a from B where value < 0 and fk_a = id)
select * from A
where id <> ALL (select fk_a from B where `value` > 0 and fk_a = A.id)
MySQL的有效查询
select * from A
where id <> ALL (select fk_a from B where `value` > 0 and fk_a = A.id)
答案 1 :(得分:1)
我将使用子查询获取具有正值的条目的FK ID,然后使用该查询的结果通过WHERE NOT IN
子句在主查询中进行过滤
模式(MySQL v5.7)
CREATE TABLE A (
`id` INTEGER PRIMARY KEY
);
INSERT INTO A
(`id`)
VALUES
(1),
(2),
(3);
CREATE TABLE B (
`id` INTEGER,
`value` INTEGER,
`fk_a` INTEGER,
FOREIGN KEY (fk_a) REFERENCES A (id)
);
INSERT INTO B
(`id`, `value`, `fk_a`)
VALUES
(1, -5, 1),
(2, -7, 1),
(3, 5, 2),
(4, -10, 3),
(5, 20, 3);
查询#1
SELECT * FROM A
WHERE A.id NOT IN
(
SELECT tb.fk_a
FROM B tb
WHERE tb.`value` >= 0
);
输出
| id |
| --- |
| 1 |