我有一个相当复杂的查询,因为我试图将数学保留在应用程序代码和查询中。我试图在选择中设置一个变量,然后在同一个选择中重复使用它。不幸的是,我使用这些变量的任何列都返回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),我不确定我是否做错了,如果是的话,如何要解决这个问题。如果需要,我可以在代码中进行数学运算,但我真的希望将它保留在数据库服务器上,因为它比应用服务器更强大,并且可以更轻松地处理这个问题。
答案 0 :(得分:0)
根据您的查询,您正在进行SUM(SUM(...))。 SUM用于将字段值加在一起,我有点怀疑变量会做同样的事情,例如..
SELECT ..
@foo := SUM(...),
@bar := SUM(@foo)
也许只是
@bar := @bar + @foo
答案 1 :(得分:0)
不幸的是,查询中的先前变量未定义。您将要么替换公式而不是替换它们。或者在代码中计算下一个变量。