使用SQL比较2个表的记录

时间:2019-03-13 21:11:56

标签: sql postgresql compare record

我有2个具有以下结构的表:

1-项表

      services.AddMvc()
       .AddXmlSerializerFormatters()
       .AddXmlDataContractSerializerFormatters();

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
);

表2

id | name   | quantity
---------------------
1  | Item 1 | 10
2  | Item 2 | 20
3  | Item 3 | 30
4  | Item 4 | 15
5  | Item 5 | 30

我需要一个查询,该查询返回的表与此类似:

id | item_id| quantity
---------------------
1  | 1      | 15
2  | 2      | 25
3  | 3      | 35
4  | 4      | 10
5  | 5      | 29

1 个答案:

答案 0 :(得分:2)

一个简单的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