gpt4 book ai didi

sql - 用 SQL 比较 2 个表的记录

转载 作者:行者123 更新时间:2023-11-29 14:28:26 25 4
gpt4 key购买 nike

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

我想获取第二个表中所有数量超过第一个表中已经定义的项目.. 例如..

表一

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

关于sql - 用 SQL 比较 2 个表的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com