php—计算两个表中的值并以单个值返回结果

91zkwejq  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(319)

如何从两个表中计算值并以单个值返回结果。?
我有两个名为order和affiliate的表,如下所示:
订单:订单id(主键)、订单名称、订单状态、附属机构id(外键)
附属公司:附属公司id(主键),附属公司名称
现在,我想通过比较order表和affiliate表上的affiliate\u id来计算基于affiliate name的订单。
我试过这样:
查询

SELECT COUNT(*) 
FROM order o  
AND (SELECT COUNT (affiliate_name) FROM affiliate a 
WHERE a.affiliate_id = O.affilate_id) AS total

它返回一个错误。

2wnc66cl

2wnc66cl1#

我不确定我是否正确理解你的问题,但这就是你要找的吗?

SELECT *, COUNT(*) as total
FROM order o  
JOIN affiliate a ON a.affiliate_id = o.affiliate_id
GROUP BY o.affiliate_id

否则,请提供样品和预期结果的例子。

gz5pxeao

gz5pxeao2#

我觉得这就是你需要的

SELECT a.affiliate_ID, a.affiliate_name, COUNT(o.order_ID) as total
FROM order o  
LEFT JOIN affiliate a ON o.affiliate_ID = a.affiliate_ID
GROUP BY o.affiliate_ID;

要添加where子句,请参见示例

SELECT a.affiliate_ID, a.affiliate_name, COUNT(o.order_ID) as total
FROM order o  
LEFT JOIN affiliate a ON o.affiliate_ID = a.affiliate_ID
WHERE o.affiliate_ID = 3
GROUP BY o.affiliate_ID;

相关问题