By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE goods (
good_id INT NOT NULL PRIMARY KEY,
good_name TEXT NOT NULL
);
CREATE TABLE payments (
payment_id INT NOT NULL PRIMARY KEY,
good INT NOT NULL,
date TIMESTAMP NOT NULL
);
CREATE INDEX payments_date ON payments (date);
Records: 0 Duplicates: 0 Warnings: 0
INSERT INTO goods(good_id, good_name)
VALUES
(1, 'Прокладки'),
(2, 'Ногточки'),
(3, 'Рестик');
Records: 3 Duplicates: 0 Warnings: 0
INSERT INTO payments(payment_id, good, date)
VALUES
(1, 1, '2004-11-11 11:11:11'),
(2, 2, '2005-11-11 11:11:11'),
(3, 3, '2005-11-11 11:11:11');
Records: 3 Duplicates: 0 Warnings: 0
EXPLAIN ANALYZE
Select g.good_name
From goods g
Left Join (
Select good
From payments
Where date Between '2005-01-01' And '2005-12-31 23:59:59.999'
) p
On g.good_id = p.good
Where p.good Is NULL;
EXPLAIN |
---|
-> Filter: (payments.good is null) (cost=5 rows=2) (actual time=0.0752..0.0815 rows=1 loops=1) -> Left hash join (payments.good = g.good_id) (cost=5 rows=2) (actual time=0.0724..0.0784 rows=3 loops=1) -> Table scan on g (cost=0.55 rows=3) (actual time=0.00773..0.0117 rows=3 loops=1) -> Hash -> Filter: (payments.`date` between '2005-01-01' and '2005-12-31 23:59:59.999') (cost=1.12 rows=2) (actual time=0.0378..0.0467 rows=2 loops=1) -> Index range scan on payments using payments_date over ('2005-01-01 00:00:00' <= date < '2006-01-01 00:00:00') (cost=1.12 rows=2) (actual time=0.025..0.0324 rows=2 loops=1) |
EXPLAIN ANALYZE
Select g.good_name
From goods g
Left Join (
Select good
From payments
Where '2005-01-01' <= date And date < '2006-01-01'
) p
On g.good_id = p.good
Where p.good Is NULL;
EXPLAIN |
---|
-> Filter: (payments.good is null) (cost=5 rows=2) (actual time=0.0406..0.0456 rows=1 loops=1) -> Left hash join (payments.good = g.good_id) (cost=5 rows=2) (actual time=0.0399..0.0447 rows=3 loops=1) -> Table scan on g (cost=0.55 rows=3) (actual time=0.0053..0.00843 rows=3 loops=1) -> Hash -> Filter: (('2005-01-01' <= payments.`date`) and (payments.`date` < '2006-01-01')) (cost=1.12 rows=2) (actual time=0.019..0.026 rows=2 loops=1) -> Index range scan on payments using payments_date over ('2005-01-01 00:00:00' <= date < '2006-01-01 00:00:00') (cost=1.12 rows=2) (actual time=0.0158..0.0219 rows=2 loops=1) |