Mysql - 如何在 where 子句中对来自不同表的两个字段进行添加

Mysql - How to make an addition on two fields from distinct tables in where clause

我有两张桌子

Invoices
  id
  discount
  voucher_id
  ...

Vouchers
  id
  discount  
  ... 

我的目标不是计算总折扣等于 100 的发票数量。

我试过了

SELECT count(*) 
FROM invoices 
LEFT JOIN vouchers ON invoices.voucher_id = vouchers.id
WHERE (invoices.discount + vouchers.discount) = 100

但这将 return 一个空结果,并且在我的数据库中,我有一些字段遵守 where 子句。

您的查询只会带回具有优惠券折扣的发票,因为您在 WHERE 子句中包含了 vouchers.discount

假设并非所有发票都有 voucher_id 值(因为您使用的是 LEFT JOIN 而不是 INNER JOIN)并且还假设发票只能永远有一张代金券.....

select count(*) from
 (
  SELECT invoices.discount+ifnull(vouchers.discount,0) as total_discount
  FROM invoices 
  LEFT JOIN vouchers ON invoices.voucher_id = vouchers.id
 ) t
where total_discount = 100;