gpt4 book ai didi

MySQL:获取具有最小值的整行

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:39 24 4
gpt4 key购买 nike

我正在尝试获取价格最低的完整行,而不仅仅是价格最低的字段。

创建表:

CREATE TABLE `Products` (
`SubProduct` varchar(100),
`Product` varchar(100),
`Feature1` varchar(100),
`Feature2` varchar(100),
`Feature3` varchar(100),
`Price1` float,
`Price2` float,
`Price3` float,
`Supplier` varchar(100)
);

插入:

INSERT INTO
`Products` (`SubProduct`, `Product`, `Feature1`, `Feature2`, `Feature3`, `Price1`, `Price2`, `Price3`, `Supplier`)
VALUES
('Awesome', 'Product', 'foo', 'foo', 'foor', '1.50', '1.50', '0', 'supplier1'),
('Awesome', 'Product', 'bar', 'foo', 'bar', '1.25', '1.75', '0', 'supplier2');

选择:

SELECT
`SubProduct`,
`Product`,
`Feature1`,
`Feature2`,
`Feature3`,
MIN(`Price1`),
`Price2`,
`Price3`,
`Supplier`
FROM `Products`
GROUP BY `SubProduct`, `Product`
ORDER BY `SubProduct`, `Product`;

您可以在 http://sqlfiddle.com/#!2/c0543/1/0 看到它

我从第二个插入的行中获取第一个插入的行,其中包含 price1 列的内容。

我希望获得包含正确功能、供应商和其他列的完整行。在此示例中,它应该是完整的第二个插入行,因为它在 price1 列中的价格最低。

最佳答案

您需要获取 MIN 价格行,然后将这些行与主表 JOIN,如下所示:

SELECT
P.`SubProduct`,
P.`Product`,
P.`Feature1`,
P.`Feature2`,
P.`Feature3`,
`Price` AS Price1,
P.`Price2`,
P.`Price3`,
P.`Supplier`
FROM `Products` AS P JOIN (
SELECT `SubProduct`, `Product`, MIN(`Price1`) AS Price
FROM `Products`
GROUP BY `SubProduct`, `Product`
) AS `MinPriceRows`
ON P.`SubProduct` = MinPriceRows.`SubProduct`
AND P.`Product` = MinPriceRows.`Product`
AND P.Price1 = MinPriceRows.Price
ORDER BY P.`SubProduct`, P.`Product`;

工作演示:http://sqlfiddle.com/#!2/c0543/20

这里我所做的是获取一个临时记录集作为 MinPriceRows 表,它将为您提供每个 SubProduct 和 Product 的 MIN 价格。然后,我将这些行与主表连接起来,以便主表行可以减少到仅包含每个子产品和产品的最低价格的行。

关于MySQL:获取具有最小值的整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22345502/

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