SELECT c.id, c.name, COUNT(*) AS Number_of_Products
FROM Product p
JOIN Category c ON (p.CategoryId=c.Id) GROUP BY c.id,c.name,p.CategoryId;
ID NAME NUMBER_OF_PRODUCTS
---------- ------------------------------ ------------------
1 LAPTOP 3
2 TV 1
SELECT c.id, c.name, COUNT(*) AS Number_of_Products
FROM Product p
JOIN Category c ON (p.CategoryId=c.Id) GROUP BY c.name,c.id,p.categoryid;
ID NAME NUMBER_OF_PRODUCTS
---------- ------------------------------ ------------------
2 TV 1
1 LAPTOP 3
以下查询由于GROUP BY顺序而导致结果不同。有人可以解释这种差异的原因吗?
谢谢!
答案 0 :(得分:1)
在内部,当RDBMS评估查询时,它会对行进行排序以便有效地执行group by
,然后,由于缺少明确的order by
子句,它会发出行内部订单。
但是,你永远不能依赖这种行为。如果您关心以特定顺序返回行的查询,则必须使用ORDER BY
子句指定该顺序。
答案 1 :(得分:0)
如果您不提供ORDER BY子句,则GROUP BY排序通常是查询结果的事实顺序(尽管这可能因RDBMS而异;并行查询可能导致结果无序排出)。
如果您想要特定的排序,请添加ORDER BY子句,例如
SELECT c.id, c.name, COUNT(*) AS Number_of_Products
FROM Product p
JOIN Category c ON (p.CategoryId=c.Id)
GROUP BY c.id,c.name,p.CategoryId
ORDER BY Number_of_Products DESC, name;