mariadb 如何获取sql查询的反向结果

nuypyhwy  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(122)

我正在使用下面的sql查询来获取一个提交了报告的分支机构的名称。

SELECT DISTINCT branch.b_name AS branch from branch, report_activity2

where branch.branch_id=report_activity2.branch_id 

and week =16
and year =2022

我还想获取在同一周和同一年没有提交报告的分行的名称。我尝试了以下查询:

SELECT branch.b_name FROM branch

WHERE branch_id not in

(SELECT DISTINCT branch.b_name AS branch from branch, report_activity2

where branch.branch_id=report_activity2.branch_id 

and week =16
and year =2022)

但是第二个查询结果列出了所有的分支,并且没有从第一个查询中排除该分支。我不确定我这样做是完全错误的,还是我只是错过了一些简单的东西。任何能把我推向正确方向的帮助都将不胜感激。

goqiplq2

goqiplq21#

在第一个示例中,您实际上不需要distinct,而且无论如何也不应该使用旧样式的join:

SELECT b_name AS branch from branch
where exists (select * from report_activity2
where branch.branch_id=report_activity2.branch_id
and report_activity2.week =16
and report_activity2.year =2022);

在第二个例子中,你应该比较branch_id和branch_,或者b_name和b_name(假设它是唯一的),但是你在(... b_bame ...)中检查branch_id。无论如何,它也不需要连接:

SELECT b_name AS branch from branch
where NOT exists (select * from report_activity2
where branch.branch_id=report_activity2.branch_id
and report_activity2.week =16
and report_activity2.year =2022);

编辑:一些更多的解释。(...),我们将检查report_activity2中是否有branch_id与“current”branch.branch_id和week = 16以及year 2022匹配的行。如果找到匹配项,则在筛选分支时将其视为true。好的方面是,可能有1或1000个匹配行。这并不重要,与连接不同,它只是停止查找第一个匹配项,因此比执行连接性能更高(在这种情况下,如果有1000行与特定的branch.branch_id匹配,则还需要DISTINCT,首先获取1000行,然后DISTINCT选择其中的1行)。
分支机构:

Branch_id, b_name
1, 'b1'
2, 'b2'

报告_活动2:

Branch_Id, Week, Year, ...
1,  1, 2022
1, 16, 2022
1, 16, 2022
1, 16, 2022
2,  1, 2022

使用join时,它看起来像(3个匹配1个):

1, 'b1', 1, 16, 2022
1, 'b1', 1, 16, 2022
1, 'b1', 1, 16, 2022

然后对b_name使用DISTINCT以获取“b1”。
存在:
开启

1, 'b1'

如果发现匹配,则首先立即返回true

1, 16, 2022

而不检查report_activity2中的其他行。结果集已经:
1,'b1'
因此,你不需要一个独特的黑客.

cs7cruho

cs7cruho2#

你能试试这个mysql命令吗?

SELECT DISTINCT branch.b_name AS branch from branch, report_activity2

where branch.branch_id != report_activity2.branch_id 

and week =16
and year =2022 ;

相关问题