gpt4 book ai didi

mysql - 在多个条件上关联 GROUP BY 和 LEFT JOIN 以显示最新记录?

转载 作者:可可西里 更新时间:2023-11-01 07:09:10 30 4
gpt4 key购买 nike

在一个简单的库存管理数据库中,添加新库存并发货,直到数量为零。每个库存变动都分配了一个引用,仅使用最新的引用。

在提供的示例中,从未显示最新的引用,股票 ID 的 1,4 应该分别引用 charlie、foxtrot,但显示的是 alpha、delta。

如何将多个条件上的 GROUP BY 和 LEFT JOIN 相关联以显示最新记录?

http://sqlfiddle.com/#!2/6bf37/107

CREATE TABLE stock (
id tinyint PRIMARY KEY,
quantity int,
parent_id tinyint
);

CREATE TABLE stock_reference (
id tinyint PRIMARY KEY,
stock_id tinyint,
stock_reference_type_id tinyint,
reference varchar(50)
);

CREATE TABLE stock_reference_type (
id tinyint PRIMARY KEY,
name varchar(50)
);

INSERT INTO stock VALUES
(1, 10, 1),
(2, -5, 1),
(3, -5, 1),
(4, 20, 4),
(5, -10, 4),
(6, -5, 4);

INSERT INTO stock_reference VALUES
(1, 1, 1, 'Alpha'),
(2, 2, 1, 'Beta'),
(3, 3, 1, 'Charlie'),
(4, 4, 1, 'Delta'),
(5, 5, 1, 'Echo'),
(6, 6, 1, 'Foxtrot');

INSERT INTO stock_reference_type VALUES
(1, 'Customer Reference');

SELECT stock.id, SUM(stock.quantity) as quantity, customer.reference
FROM stock
LEFT JOIN stock_reference AS customer ON stock.id = customer.stock_id AND stock_reference_type_id = 1
GROUP BY stock.parent_id

最佳答案

您可以使用子查询来获取每个股票组的最新 ID:

SELECT g.parent_id, g.quantity, customer.reference
FROM (
SELECT parent_id, SUM(stock.quantity) as quantity, MAX(id) as LatestID
FROM stock
GROUP BY parent_id
) g LEFT JOIN stock_reference AS custome
ON g.LatestID = customer.stock_id AND stock_reference_type_id = 1

关于mysql - 在多个条件上关联 GROUP BY 和 LEFT JOIN 以显示最新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12355187/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com