选择唯一的产品 ID 并按库存 ID 说明订购


Select unique product id and order by stock id desc

我正在尝试从库存中获得独特的产品...

库存表:

id - product - quantity
1    2            0
2    3            5
3    2            19
4    4            3
5    2            8

结果

id - product - quantity
5    2            8
4    4            3
2    3            5

它正在与

SELECT max(id) as id, 
product
FROM stock 
GROUP by product 
ORDER by id DESC

但我无法获得最后数量的产品通过此查询,我得到:

id - product - quantity
1    2            0
2    3            5
4    4            3

我需要最新数量的产品。

您可以将现有查询包装在子查询中,并将其联接到表本身上,以便获取同一行的其他列。

SELECT  a.*
FROM    stock a
        INNER JOIN
        (
            SELECT  product, MAX(ID) id
            FROM    stock
            GROUP   BY product
        ) b ON  a.product = b.product
                AND a.ID = b.ID
ORDER   BY a.id DESC

假设您对"latest"的定义是max(id),我认为最简单的方法是:

SELECT s.id, s.product, s.quantity
FROM stock s
WHERE NOT EXISTS (SELECT 1 FROM stock s2 WHERE s2.product = s.product and s2.id > s.id);

基本上给我库存行,其中没有具有更大 id 的同一产品的行。

您可以使用表本身的左连接来做到这一点,该连接仅过滤没有具有更高 id 和相同乘积的行,避免子查询和分组依据,这在大型表上可能非常昂贵:

select p1.id, p1.product, p1.quantity from stock as p1 
left join test as p2 on p1.product = p2.product and p2.id> p1.id
where p2.id is null
order by p1.id desc;