小编Sel*_*azi的帖子

为什么使用联接的查询比使用子查询慢得多?

我很惊讶我使用的查询join比使用子查询慢了大约 350 倍。通常,我更喜欢使用 join,因为它更具可读性。但是,速度上的差距实在是太大了。

这是数据定义。这些表直接从源代码中提取(除了下面注释的那些行)。

-- possible account type for char of accounts below.
create type account_kind as enum (
  'asset',
  'liability',
  'equity',
  'income',
  'expense'
);

-- chart of accounts represented as a tree.
create table account(
  id        integer      not null,
  name      text         not null,
  kind      account_kind not null,
  parent_id integer,

  constraint account_pkey primary key (id),
  constraint account_name_length_check check (length(name) between 1 and 200),
  constraint account_parent_id_fkey foreign key (parent_id) references account(id) on update cascade on delete restrict,
  constraint …
Run Code Online (Sandbox Code Playgroud)

postgresql join subquery query-optimization

5
推荐指数
0
解决办法
61
查看次数

通过连接从两个表求和

假设我有两个包含 2 列的表: 表 A

工作 成本
1 100
1 200
2 100
2 150
2 50

和表B:

工作
1 100
1 100
1 200
2 100
2 100

我想通过连接这两个表来查询结果,如下所示:

工作 成本
1 300 400
2 300 200

我尝试如下查询,但结果不符合预期:

SELECT A.Job, 
       SUM(A.Cost) AS NCOST,
       SUM(B.Sell) AS NSELL   
FROM TableA A 
JOIN TableB B ON A.Job= B.Job
GROUP BY A.Job;
Run Code Online (Sandbox Code Playgroud)

谁能帮助我纠正我的查询?

mysql sql

1
推荐指数
1
解决办法
120
查看次数

标签 统计

join ×1

mysql ×1

postgresql ×1

query-optimization ×1

sql ×1

subquery ×1