我有两个表,一个用于存储用户收入,另一个用于存储用户付款。我想做的是获得最低50美元的付款,并且只能从最后一次付款中获得。
表(userEarnings)包含以下列
id ->autoincrement
userid -> unique id for users
earn ->the amount of money the user earn (25.00, 14.50..)
date_added -> DATETIME column
每次用户获得付款时,第二个表(userPayment)都会存储
pid->autoincrement
uid ->unique user id, this is the same as userid from the above table
paid_amt->payments the user received(500.00, 100.00...)
paid_date ->the date the user was paid(DATETIME)
从这两张表中,如果金额超过50美元,我想列出自上次付款以来的用户ID和欠款总和。我假设我需要使用子查询和组,但不知道从哪里开始。
非常感谢任何帮助。感谢
答案 0 :(得分:1)
试试这个:
SELECT userEarnings.userid, SUM(earn) AS total_earn FROM (
SELECT uid, MAX(paid_date) AS paid_date
FROM userPayment
GROUP BY uid) AS T1
RIGHT JOIN userEarnings ON T1.uid = userEarnings.userid
WHERE date_added > T1.paid_date OR T1.paid_date IS NULL
GROUP BY userEarnings.userid
HAVING total_earn > 50
答案 1 :(得分:1)
SELECT userEarnings.userid, SUM(userEarnings.earn) AS earn FROM userEarnings LEFT OUTER JOIN ( SELECT uid, MAX(paid_date) AS last_payment FROM userPayment GROUP BY uid) AS q ON q.uid = userEarnings.userid --the q.last_payment IS NULL clause ensures that the user who never got a payment before will get his first $50 check WHERE (userEarnings.date_added > q.last_payment) OR (q.last_payment IS NULL) GROUP BY userEarnings.userid HAVING SUM(userEarnings.earn) >= 50.0
答案 2 :(得分:0)
使用not exists
子查询稍有不同的方法。可以以不同的方式执行,并且可能更容易阅读,具体取决于品味。
SELECT ue.userid User
, SUM(ue.earn) AmountDue
FROM userEarnings ue
WHERE NOT EXISTS (
SELECT *
FROM userPayment up
WHERE up.uid = ue.userid
AND up.paid_date >= ue.date_added
)
GROUP BY ue.userid
HAVING AmountDue > 50.0