我正在尝试创建一个 SQL 语句,该语句将允许我对用户计算的性能结果进行分页。任何帮助将不胜感激。这是我正在尝试做的事情的模型:
我有4张桌子..
用户
usersid | name etc...
1 | Satoshi
2 | Musk
金额课程
lessonsid | usersid | totalPay
1 | 1 | 200
2 | 1 | 375
工作
jobsid | usersid..
1 | 1
2 | 1
3 | 1
4 | 1
5 | 1
工作机会
offersid | usersid..
1 | 1
2 | 1
3 | 1
4 | 1
5 | 1
6 | 1
7 | 1
8 | 1
9 | 1
我需要按照下面的逻辑描述进行操作
SELECT users.*,
'get all users',
'The SUM(totalPay) FROM lessons, if there are no lessons then return 0 - AS totalSum',
'The COUNT(jobid) FROM jobs WHERE usersid=id, if there are no jobs then return 0 - AS greens',
'The COUNT(id) FROM offers WHERE usersid=id, if there are no offers then return 0 - AS golds'
FROM
users
LEFT JOIN
'Left join tables USING usersid? I need all the data from the users table regardless of whether there is data available in the joined tables. If there is no data in the joined tables then variables need to have a zero int value as in the SELECT statement'
'lessons'
'jobs'
'offers'
DO CALCULATION - Calculate a score for the user (I have used php as an example)
'user_score = 0;
if (greens>0 && golds>0){
user_score = (greens/golds) * totalSum;
user_score = round(user_score);
}'
ORDER BY user_score DESC
期望的结果应显示以下内容;
userid: 1 greens=5, golds=9, totalsum=575 -> user_sore=5/9*575=319
userid: 2 user_sore=0
usersid | user_score | name etc
1 | 319 | Satoshi
2 | 0 | Musk
您只需连接所有表,并需要将最终计算放在最终的 select 语句中,如下所示 -
SELECT U.usersid, COALESCE(ROUND(job_count/job_offer_count*total_pay), 0) user_score, name
FROM USERS U
LEFT JOIN (SELECT usersid, SUM(totalPay) total_pay
FROM LESSONS
GROUP BY usersid) L ON U.usersid = L.usersid
LEFT JOIN (SELECT usersid, COUNT(*) job_count
FROM JOBS
GROUP BY usersid) J ON U.usersid = J.usersid
LEFT JOIN (SELECT usersid, COUNT(*) job_offer_count
FROM JOB_OFFERS
GROUP BY usersid) JO ON U.usersid = JO.usersid;