我有一张表user(id,name)
和一张表payments(date,amount,user_id)
我需要一个查询,以便为每个用户显示上个月的付款总额和付款。
User - totalpayments - monthlypayments
类似这样的事情
SELECT id, name from user;
SELECT COUNT(amount) FROM payments WHERE user_id=user.id;
SELECT COUNT(amount) FROM payments WHERE user_id=user.id AND (data<=$timestamptoday AND data>=$timestamp1stday)
可以在不做多次查询的情况下做到这一点吗?
答案 0 :(得分:2)
当然,您可以在一个查询中执行此操作。
SELECT
u.ID,
u.Name,
SUM(p.amount),
SUM(CASE
WHEN p.date <= '2013-02-01' AND p.date >= '2013-01-01' THEN p.amount
ELSE 0
END)
FROM
Users u
JOIN
Payments p ON u.ID = p.UserID
GROUP BY
u.ID,
u.Name
工作DEMO
答案 1 :(得分:0)
绝对可以将其作为单个查询执行:
SELECT user.name, SUM(amount) AS totalpayments, SUM(IF(date <= '$enddate' AND date >= '$startdate'),amount,0) AS monthlypayments
FROM user LEFT JOIN payments ON user.id = payments.user_id
GROUP BY user.id
ORDER BY user.name ASC
请注意,我假设您正在查找付款总额,而不是付款次数,我使用SUM
而不是COUNT
。