Сравните записи 2 таблиц с SQL - PullRequest
0 голосов
/ 14 марта 2019

У меня есть 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

1 Ответ

2 голосов
/ 14 марта 2019

Простой 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
...