MySQL与表达式连接
我有两张桌子。一个包含项目数量的优惠,第二个包含项目对优惠的分配。我正在尝试编写一个查询,该查询生成一个表,显示每个报价项的报价金额和总分配金额 示例表'offers':MySQL与表达式连接,mysql,join,Mysql,Join,我有两张桌子。一个包含项目数量的优惠,第二个包含项目对优惠的分配。我正在尝试编写一个查询,该查询生成一个表,显示每个报价项的报价金额和总分配金额 示例表'offers': +----+----+----+ |oid |uid |amt | +----+----+----+ | 1| 413| 10| | 2| 297| 7| +----+----+----+ 示例表“分配”: +----+----+------+ |aid |oid |alloc | +----+----+---
+----+----+----+
|oid |uid |amt |
+----+----+----+
| 1| 413| 10|
| 2| 297| 7|
+----+----+----+
示例表“分配”:
+----+----+------+
|aid |oid |alloc |
+----+----+------+
| 1| 2| 4|
| 2| 2| 2|
+----+----+------+
我希望得到以下结果:
+----+----+------+
|oid |amt |alloc |
+----+----+------+
| 1| 10| 0|
| 2| 7| 6|
+----+----+------+
我尝试了以下查询:
SELECT `offers`.`oid`, `offers`.`amt`, COALESCE(SUM(`allocations`.`alloc`),0)
FROM `offers`
LEFT JOIN `allocations` ON `allocations`.`oid`=`offers`.`oid`
但是,总和作用于整个表,而不仅仅是满足
`allocations`.`oid`=`offers`.`oid`
没有分配的优惠不会打印。尝试使用分组方式
SELECT `offers`.`oid`, `offers`.`amt`, COALESCE(SUM(`allocations`.`alloc`),0)
FROM `offers`
LEFT JOIN `allocations` ON `allocations`.`oid`=`offers`.`oid`
GROUP BY offers.oid
(我假设offers.oid
是您的主键?)
严格地说,应该是这样
GROUP BY offers.oid, offers.amt
也就是说,任何不是聚合函数结果的列都必须列在
GROUP BY
子句中。有些服务器配置为强制执行此操作,而有些服务器则不执行此操作。除非提供group by子句,否则任何聚合函数(如sum())都将在整个结果集中运行
SELECT `offers`.`oid`, `offers`.`amt`, COALESCE(SUM(`allocations`.`alloc`),0)
FROM `offers`
LEFT JOIN `allocations` ON `allocations`.`oid`=`offers`.`oid`
GROUP BY `offers`.`oid`, `offers`.`amt`
但是,我没有得到“没有分配的报价不打印”部分,因为左连接应该处理这一点,除非在实际查询中两个表的顺序颠倒。因此这里您必须使用group by子句对每个oid进行求和
SELECT `offers`.`oid`, `offers`.`amt`, COALESCE(SUM(`allocations`.`alloc`),0) FROM `offers`
LEFT JOIN `allocations` ON `allocations`.`oid`=`offers`.`oid` group by oid
然后你将代码迁移到启用了严格sql模式的mysql服务器上,你会想知道为什么你的代码停止工作…@Shadow修复了它。现在快乐吗?