我有2个表具有以下结构:
1个项目表
create table if not exists items
(
id bigserial not null primary key,
group_id integer not null,
description text not null,
quantity double precision not null,
measurement_id integer not null,
model varchar(255),
unitary double precision not null,
price double precision not null,
currency_id integer not null
);
1雇用表
create table if not exists hireds
(
id bigserial not null primary key,
item_id integer not null constraint hireds_item_id_foreign references items on delete cascade,
quantity double precision not null,
price double precision not null
);
我想在第二个表中获取其数量的所有项目超过第一个中已经定义的。例如..
表1
id | name | quantity
---------------------
1 | Item 1 | 10
2 | Item 2 | 20
3 | Item 3 | 30
4 | Item 4 | 15
5 | Item 5 | 30
表2
id | item_id| quantity
---------------------
1 | 1 | 15
2 | 2 | 25
3 | 3 | 35
4 | 4 | 10
5 | 5 | 29
我需要一个与此类似的表返回表的查询:
id | item_id| quantity
---------------------
1 | 1 | 5
2 | 2 | 5
3 | 3 | 5
简单的JOIN
会做:
select
i.id,
h.item_id,
h.quantity - u.quantity as quantity
from items i
join hireds h on h.item_id = i.id
where i.quantity < h.quantity
order by i.id