我很惊讶我使用的查询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) 假设我有两个包含 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)
谁能帮助我纠正我的查询?