且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LEFT JOIN 查询中的 SUM

更新时间:2022-11-30 18:15:40

不要想太多.只需用加号将它们加在一起即可.

Don't overthink it. Just add them together with a plus sign.

SELECT products.ID, products.Base, COUNT(orders.ID) AS Counter,
products.Base + COUNT(orders.ID) as `SUM`
FROM products 
LEFT JOIN orders ON products.ID = orders.Product_ID 
GROUP BY products.ID
ORDER BY `SUM`

注意:SUM"是聚合 SQL 函数的名称,因此您需要用反引号将其括起来,以便将其用作列别名.考虑使用不同的名称.

Note: "SUM" is the name of an aggregate SQL function so you'll need to surround it in backticks in order to use it as a column alias. Consider using a different name.