2

我有两张表,一张包含报价信息,另一张包含类似这样的产品:

           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) 应该被计算在内。

我应该如何最好地查询这个?

4

4 回答 4

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));
于 2013-08-23T12:47:30.593 回答
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
于 2013-08-23T12:44:39.367 回答
0

如果idversion相关:

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
于 2013-08-23T12:54:10.037 回答
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

如果您需要除offernumber 和id 之外的offer 中的其他列:

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 
于 2013-08-23T13:00:56.353 回答