gpt4 book ai didi

SQL查询以获得预期结果

转载 作者:行者123 更新时间:2023-11-29 01:33:15 25 4
gpt4 key购买 nike

这是我的数据库架构

Table_A
-id
-status

Table_B
-id

Table_A_has_B
-id
-id_A
-id_B

我需要从 Table_B 中选择所有记录,其中所有关联的 Table_A 记录都有 status=1,如果 Table_B 记录没有任何关联的 Table_A,也应该选择。

测试用例:

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);

查询应该选择:

+----+
|b.id|
+----+
| 2|
| 3|
| 4|
+----+
  • 不应选择 ID 1,因为其 table_a 记录之一的状态为 0
  • id 2 和 4 应该被选中,因为它的所有 table_a 记录都有 status=1
  • 应该选择 Id 3,因为没有关联的 table_a 记录,同一标准的另一个观点是:应该选择 Id 3,因为没有任何 table_a 记录,其中 status=0

最佳答案

编辑答案 -

select b.* from table_B b 
left outer join table_A_has_B ab on ab.id_B = b.id
where ab.id in (
select id from table_A_has_B ab
where (id_A in (select id from table_A where status = 1 ))
)
or b.id not in
(select id_B from table_A_Has_B )

旧答案 -

select b.* from table_B b
left outer join table_A a on b.id = a.id
where a.status = 1 or a.id is null

关于SQL查询以获得预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5044539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com