我想优化查询SQL。

huangapple go评论65阅读模式
英文:

I want to optimize the query-sql

问题

以下是已翻译的内容:

由于数据库中有大量数据,查询不起作用,我需要将一个层中的值与另一个层中的值进行比较,找到新层中不在旧层中的那些值。

这是我的查询:

select distinct id_gs,nmbr_tusa
from "NEW_SLOY"."SHILPU"
where date_contract >= '2023-05-01'
and id_gs not in(select id_gs from "OLD_SLOY"."SHILPU")
英文:

since there is a lot of data in the database, the query does not work, I need to compare values from one layer with another, find those values from the new layer that are not in the old one.

THIS IS MY QUERY:

select distinct id_gs,nmbr_tusa
from "NEW_SLOY"."SHILPU"
where date_contract  >= '2023-05-01'
and id_gs not in(select id_gs from "OLD_SLOY"."SHILPU")

答案1

得分: 1

不使用子查询,可以使用 left join

SELECT DISTINCT N.id_gs, N.nmbr_tusa
FROM "NEW_SLOY"."SHILPU" N
LEFT JOIN "OLD_SLOY"."SHILPU" O
ON N.id_gs = O.id_gs
WHERE N.date_contract >= '2023-05-01'
AND O.id_gs IS NULL;

当子查询中有大量行时,它会将主查询中的每一行与子查询中的每一行进行比较,导致大量的比较。

您可以在这里了解更多关于 left join 的信息:
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-left-join/

英文:

Instead of subquery, you can use left join.

SELECT DISTINCT N.id_gs, N.nmbr_tusa
FROM "NEW_SLOY"."SHILPU" N
LEFT JOIN "OLD_SLOY"."SHILPU" O
ON N.id_gs = O.id_gs
WHERE N.date_contract >= '2023-05-01'
AND O.id_gs IS NULL;

When you have a lot of rows in a subquery. It compares every row in a main query with every row in a subquery. It leads to a huge number of comparisons.

you can read more about left join here:
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-left-join/

huangapple
  • 本文由 发表于 2023年6月27日 18:22:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定