MySQL 两个 Table 最小值和分组依据
MySQL Two Table Min Value and Group By
我有两个表,产品和 products_description
产品:
Product_ID Product_Price
1 10
2 20
3 10
4 20
5 10
6 20
7 10
8 10
9 10
10 10
Products_Description:
Product_ID Product_Name
1 Pants - Black
2 Pants - Black
3 Pants - White
4 Pants - White
5 Pants - Red
6 Pants - Red
7 Hat
8 Socks
9 Scarf
10 Bird
基本上我需要根据购物车中已经存在的当前代码来实现代码。
实施需要 GROUP BY products_name - 但提供最便宜的。
到目前为止我得到了以下信息:
SELECT p.products_id, p.products_price, pd.products_name
FROM products p
// bof自定义子查询
join
(
SELECT pp.products_id, pp.products_name, min(pr.products_price) as min_price
from products_description pp
inner JOIN products pr
ON pp.products_id = pr.products_id
group by pp.products_name
)
AS subq on p.products_id = subq.products_id and p.products_price = subq.min_price
//eof自定义子查询
LEFT JOIN products_description pd on p.products_id = pd.products_id
期望的输出:
Product_ID Product_Name Product_Price
1 Pants - Black 10
3 Pants - White 10
5 Pants - Red 10
7 Hat 10
8 Socks 10
9 Scarf 10
10 Bird 10
但是发生的事情是裤子被脱掉了。只剩下第 7 - 10 个产品....
有什么想法吗?
您似乎想要每个产品名称中最便宜的产品。查询有点复杂,因为价格和名称信息是分开的。一种编写查询的方法是:
select p.Product_ID, ppd.Product_Name, p.price
from product_description pd join
products p
on pd.product_id = p.product_id join
(select pd2.Product_name, min(p2.price) as minprice
from product_description pd2 join
products p2
on pd2.product_id = p2.product_id
group by pd2.Product_name
) ppd
on ppd.Product_Name = pd.Product_Name and
ppd.minprice = p.price;
我有两个表,产品和 products_description
产品:
Product_ID Product_Price
1 10
2 20
3 10
4 20
5 10
6 20
7 10
8 10
9 10
10 10
Products_Description:
Product_ID Product_Name
1 Pants - Black
2 Pants - Black
3 Pants - White
4 Pants - White
5 Pants - Red
6 Pants - Red
7 Hat
8 Socks
9 Scarf
10 Bird
基本上我需要根据购物车中已经存在的当前代码来实现代码。
实施需要 GROUP BY products_name - 但提供最便宜的。
到目前为止我得到了以下信息:
SELECT p.products_id, p.products_price, pd.products_name
FROM products p
// bof自定义子查询
join
(
SELECT pp.products_id, pp.products_name, min(pr.products_price) as min_price
from products_description pp
inner JOIN products pr
ON pp.products_id = pr.products_id
group by pp.products_name
)
AS subq on p.products_id = subq.products_id and p.products_price = subq.min_price
//eof自定义子查询
LEFT JOIN products_description pd on p.products_id = pd.products_id
期望的输出:
Product_ID Product_Name Product_Price
1 Pants - Black 10
3 Pants - White 10
5 Pants - Red 10
7 Hat 10
8 Socks 10
9 Scarf 10
10 Bird 10
但是发生的事情是裤子被脱掉了。只剩下第 7 - 10 个产品....
有什么想法吗?
您似乎想要每个产品名称中最便宜的产品。查询有点复杂,因为价格和名称信息是分开的。一种编写查询的方法是:
select p.Product_ID, ppd.Product_Name, p.price
from product_description pd join
products p
on pd.product_id = p.product_id join
(select pd2.Product_name, min(p2.price) as minprice
from product_description pd2 join
products p2
on pd2.product_id = p2.product_id
group by pd2.Product_name
) ppd
on ppd.Product_Name = pd.Product_Name and
ppd.minprice = p.price;