我有一个相当复杂的查询,因为我试图将数学排除在应用程序代码和查询之外。我试图在选择中设置一个变量,然后在同一个选择中重新使用它。不幸的是,我使用这些变量的任何列都在应该有数据的地方返回 null。其他一切工作正常。
SELECT @signups:= COUNT(registrations.id) as signups,
@registrations:= SUM(IF(registrations.fees_paid_by_users = '1', registrations.amount - registrations.databar_fees - registrations.taxes - registrations.extras_price + registrations.discount_total, registrations.amount - registrations.taxes - registrations.extras_price + registrations.discount_total)) as registrations,
@activities:= SUM(registrations.extras_price) as activities,
@coupons:= SUM(discount_total) as coupons,
@subtotal:= @registrations + @activities - @coupons as subtotal,
@fees_not_paid_by_user:= SUM(IF(registrations.fees_paid_by_users = '0', registrations.databar_fees, 0)) as fees_not_paid_by_user,
@taxes:= SUM(registrations.taxes) as taxes,
@total_including_taxes:= @subtotal - @fees_not_paid_by_user + @taxes as total_including_taxes,
events.name,
event_forms.title ,
event_forms.id,
CONCAT(users.first_name, ' ', users.last_name) as user_name
FROM registrations,
events,
event_forms,
transactions,
users
WHERE transactions.date >= '2013-09-01 00:00:00'
AND transactions.date <= '2013-09-30 23:59:59'
AND registrations.transaction_id = transactions.id
AND registrations.event_forms_id = event_forms.id
AND event_forms.event_id = events.id
AND events.owner_id = users.id
GROUP BY registrations.event_forms_id
ORDER BY user_name ASC, name ASC, title ASC
在上面的查询中,subtotal
和total_including_taxes
列返回 null,我假设是因为查询无法访问先前定义的变量。
这是我第一次真正使用 MySQL 的用户变量(我是开发人员,而不是 DBA),我不确定我是否做错了什么,如果是,如何修复它。如果需要,我可以在代码中进行数学运算,但我真的很想将它保留在数据库服务器上,因为它比应用程序服务器更强大,并且可以更轻松地处理这个问题。