我想我已经盯着这个问题太久了。我们接管了系统的维护,并试图修复其中的一份报告。出于某种原因,除了本报告中的一个之外,所有数字都是正确的,我对这个问题没有任何运气。
以下查询显示数据库中有 1014 个事务:
SELECT COUNT(DISTINCT(store_orders_id))
FROM transactions, store_orders_products
WHERE store_orders_products.store_orders_id = transactions.id
AND transactions.date >= '2013-10-01 00:00:00'
AND transactions.date <= '2013-10-31 23:59:59'
AND store_orders_products.category_name <> ''
DISTINCT() 调用是必要的,因为 store_orders_products 包含每个订购产品的一行,因此对于具有多个产品的订单,store_orders_id 将有重复。上面的查询产生正确的结果。这些日期之间实际上有 1014 笔交易。
这就是问题所在。当我们运行完整的报告查询时,返回的总数为 1030。
SELECT COUNT(DISTINCT(store_orders_id)) as transactions,
SUM(store_orders_products.total + store_orders_products.coupon) as total,
SUM(store_orders_products.coupon) as coupon,
SUM(store_orders_products.shipping) as shipping,
SUM(store_orders_products.tax) as tax, store_orders_products.category_name
FROM transactions, store_orders_products
WHERE store_orders_products.store_orders_id = transactions.id
AND transactions.date >= '2013-10-01 00:00:00'
AND transactions.date <= '2013-10-31 23:59:59'
AND store_orders_products.category_name <> ''
GROUP BY store_orders_products.category_name
ORDER BY store_orders_products.category_name ASC
这会生成如下报告:
Transactions | Total | Coupon | Shipping | Tax | Category Name
483 | 17863.15 | 0.00 | 1493.50 | 260.56 | Category 1
547 | 21541.47 | 0.00 | 1594.80 | 194.03 | Category 2
如您所见,这些交易的总和是 1030,而不是我们预期的 1014。
当我们简单地添加第二个选定的列时,似乎会出现问题。例如,在上面发布的第一个查询块中将 from 更改为SELECT COUNT(DISTINCT(store_orders_id))
导致SELECT COUNT(DISTINCT(store_orders_id)), store_orders_products.category_name
从 1014 个结果跳转到 1030 个结果。
我希望我已经提供了足够有用的信息。我确定这是查询的问题,但正如我所说,我们刚刚接管了这个项目并且仍然习惯了事情,所以我们现在尽量不要从头开始重写任何东西。