我尝试获取按组排序的产品组列表。 我的问题是我只需要将一个产品放入一个可用的组中(0 =不,1 =是),并且最低价格和金额> 0。
select id, group_id, price, amount, available from products
Table rows:
id group_id price amount available
1 1 100 1 1
2 1 50 1 1
3 1 25 1 0
4 2 100 2 1
5 2 200 1 1
6 2 100 2 1
7 2 50 1 1
我需要id为2和7的行作为结果。 我的问题是在group_id中有多个具有相同价格的ID。
没有子选择解决这个问题的想法吗?
答案 0 :(得分:1)
这是ANSI标准,应该返回你想要的。如果有多个符合条件的行(即具有相同的最小价格),则只返回第一个(较低的id)。
SELECT MIN(P.id), P.group_id, P.price, P.amount, P.available
FROM products P
INNER JOIN
(SELECT group_id, MIN(price) AS minprice
FROM products
WHERE available=1 AND amount > 0
GROUP BY group_id
) G ON P.group_id = G.group_id AND P.price = G.minprice
GROUP BY P.group_id, P.price, P.amount, P.available
ORDER BY P.group_id
请注意,如果您有一个大表,您可能需要索引价格列(或复合索引group_id +价格)
在其他支持窗口函数的RDBMS上会更简单
答案 1 :(得分:0)
您可以在HAVING上使用MIN子句和GROUP BY,如下所示:
CREATE TABLE products (
id INT PRIMARY KEY NOT NULL,
group_id INT NOT NULL,
price INT NOT NULL,
amount INT NOT NULL,
available INT NOT NULL
);
INSERT INTO products (id, group_id, price, amount, available) VALUES (1, 1, 100, 1, 1);
INSERT INTO products (id, group_id, price, amount, available) VALUES (2, 1, 50 , 1, 1);
INSERT INTO products (id, group_id, price, amount, available) VALUES (3, 1, 25 , 1, 0);
INSERT INTO products (id, group_id, price, amount, available) VALUES (4, 2, 100, 2, 1);
INSERT INTO products (id, group_id, price, amount, available) VALUES (5, 2, 200, 1, 1);
INSERT INTO products (id, group_id, price, amount, available) VALUES (6, 2, 100, 2, 1);
SELECT id, group_id, price, amount, available FROM products;
SELECT id, group_id, price, amount, available
FROM products
WHERE amount > 0
AND available = 1
GROUP BY group_id HAVING min(price);