我有两张表,其中包含提供信息和其他包含产品的信息 像这样的东西:
OFFER PRODUCTS
ID Number Version poID offer_id Product how_many
========================== ========================================
1 123 1 1 1 Apple 1
2 123 2 2 1 Banana 2
3 124 1 3 1 Orange 1
4 2 Apple 1
5 2 Banana 2
6 2 Orange 2
7 2 Kiwi 1
8 3 Apple 2
9 3 Banana 3
我想列出目前提供的产品数量。 由于OFFER(id = 2)是(id = 1)的更新,因此只应计算(id = 2)。
我该如何最好地查询?
答案 0 :(得分:1)
首先,您需要获得所有最新的优惠:
select o.id
from offer o
where version = (select max(version)
from offer o2
where o2.number = o.number);
基于以上所述,您可以获得所有产品:
select p.*
from products p
where offer_id in (select o.id
from offer o
where version = (select max(version)
from offer o2
where o2.number = o.number));
答案 1 :(得分:0)
SELECT *
FROM products
WHERE offer_id = (SELECT MAX(id) FROM offer)
或者,如果您更喜欢连接语法
SELECT p.*
FROM products p
INNER JOIN (SELECT MAX(id) id FROM offer) o ON p.offer_id = o.id
编辑(仍然不完全确定这是你想要的,而不会看到你想要的结果)
SELECT p.*
FROM products p
INNER JOIN offer o on p.offer_id = o.id
INNER JOIN
(SELECT number, max(version)
FROM offer
GROUP BY number
) oMax ON o.number = oMax.number AND o.version = oMax.version
答案 2 :(得分:0)
如果id
和version
相关:
select sum(how_many) from products p
join offer on p.offer_id=offer.id
join (
select number, max(version) version from offer group by number
) x
on offer.id=x.id and offer.version = x.version
答案 3 :(得分:0)
试试这个:
select [list columns here]
from products p
join (select offernumber, max(id) as ID from offer group by offernumber) a
on a.id = p.offer_id
如果您需要提供除要约编号和ID以外的其他列:
select [list columns here]
from products p
join (select offernumber, max(id) as ID from offer group by offernumber) a
on a.id = p.offer_id
join offer o on o.id = a.id