我正在尝试在单个查询中获取与产品相关的所有单位
将不胜感激任何帮助
Table Product
ID Product_Name
1 Tomato
2 Banana
3 Sugar
4 Potatto
Table Units
ID ProductID Quantity Unit
1 3 1 KG
2 3 2 KG
3 3 3 KG
4 3 5 KG
Expected Result
ID 1, Product_Name Sugar, [Quantity 1 Unit KG] [Quantity 2 Unit KG] [Quantity 3 Unit KG] [Quantity 5 Unit KG]
加入 Products
和 Units
后,您可以将结果group
by
产品列,然后使用 GROUP_CONCAT
聚合函数获取产品所需的单位列表:
SELECT p.ID, p.Product_Name, GROUP_CONCAT(CONCAT('[Quantity:', u.Quantity, ' Unit:',u.Unit,']')) as UnitList
FROM Units u JOIN Product p
ON p.ID = u.ProductId
WHERE p.ID = 3 // or any other product id
GROUP BY p.ID, p.Product_Name