我有一个这样的表(通过连接不同的表创建)
+------------+--------------+-------------+
| product_id | product_name | category_id |
+------------+--------------+-------------+
| 1 | orange | 3 |
| 1 | orange | 4 |
| 2 | banana | 2 |
| 3 | apple | 2 |
| 3 | apple | 3 |
| 3 | apple | 4 |
+------------+--------------+-------------+
我希望它按ID组合在一起,但按名称排序。
喜欢这个
+------------+--------------+-------------+
| product_id | product_name | category_id |
+------------+--------------+-------------+
| 3 | apple | 2 |
| 3 | apple | 3 |
| 3 | apple | 4 |
| 2 | banana | 2 |
| 1 | orange | 3 |
| 1 | orange | 4 |
+------------+--------------+-------------+
这可能吗?我尝试使用GROUP BY,但是每个产品只保留一行,所以我看不到所有类别的产品。
编辑:我的查询到目前为止
SELECT products.id as product_id, products.name as product_name, categories.id as category_id
FROM produkte
LEFT JOIN prod_cat ON products.id = prod_cat.product_id
JOIN categories ON prod_cat.category_id = categories.id
ORDER BY products.id
“prod_cat”是为产品分配类别的表。
答案 0 :(得分:1)
Select * from products order by product_id desc, product_name asc;
答案 1 :(得分:1)
这将按名称和类别ID对它们进行排序,并按照您显示的结果给出结果。
SELECT products.id as product_id, products.name as product_name, categories.id as category_id
FROM produkte
LEFT JOIN prod_cat ON products.id = prod_cat.product_id
JOIN categories ON prod_cat.category_id = categories.id
ORDER BY product_name ASC, category_id ASC
我认为您误解了GROUP BY,但如果您想对它们进行分组(将记录减少到GROUP BY子句中给出的字段匹配的记录),您可以使用GROUP_CONCAT(categories.id)
将类别显示为列表与GROUP BY product_id