如何计算两个表中的值并将结果返回一个值。?
我有两张名为order and affiliate的表,如下所示:
顺序: order_ID(主键),order_name,Order_status,affiliate_ID(外键)
联盟: affiliate_ID(主键),affiliate_name
现在,我想通过比较订单表和会员表上的affiliate_ID来计算基于会员名称的订单。
我试过这样的话:
查询
SELECT COUNT(*)
FROM order o
AND (SELECT COUNT (affiliate_name) FROM affiliate a
WHERE a.affiliate_id = O.affilate_id) AS total
它返回错误。
答案 0 :(得分:2)
我觉得这就是你需要的东西
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;
答案 1 :(得分:0)
我不确定我是否正确理解了您的问题,但这是您正在寻找的吗?
SELECT *, COUNT(*) as total
FROM order o
JOIN affiliate a ON a.affiliate_id = o.affiliate_id
GROUP BY o.affiliate_id
否则,提供样本&请求结果示例。