我目前正在运行以下查询,该查询返回一组作业及其类别和发布该作业的人的用户名。
SELECT job_id, user_id, title, profiles.user_name
FROM (jobs)
JOIN profiles ON jobs.user_id = profiles.user_id
JOIN job_categories ON jobs.cat_id = job_categories.cat_id
JOIN job_sub_categories ON jobs.sub_cat_id = job_sub_categories.sub_cat_id
WHERE `status` = 'open'
ORDER BY post_date desc
LIMIT 5
我有一个名为反馈的表格,根据以前的交易为特定雇主提供大量反馈(很像ebay)。
feedback_id|employer_id|job_id|performance_score|quality_score|availability_score|communication_score
我希望能够根据雇主当前的反馈评级对结果进行排序和过滤,我不知道如何将其添加到我的查询中。好像我必须在查询中做一些数学运算或者运行一个子查询?或者我应该修改我的反馈表以包含另一个字段,例如为特定评级提供的总反馈?
非常感谢任何帮助。
评分是根据加在一起的所有反馈分数除以行数除以数字4计算的,因为有4个评分字段(性能,质量,可用性和通信),因此feedback_avg = (feedback_total/num_rows)/4
答案 0 :(得分:1)
让我试一试。我假设您只有两个表,employers: [id, name]
和feedback: [id, employer_id, score]
。
首先,得分子查询:
SELECT employer_id, SUM(score) AS total_score, COUNT(*) AS num_rows
FROM feedback GROUP BY employer_id;
现在主要查询:
SELECT name, total_score/num_rows AS avg_score
FROM employers JOIN ([subquery]) AS sq ON(employers.id = sq.employer_id)
WHERE avg_score > 0.5;
将整个子查询粘贴到指定的位置。
提示:观看次数
如果您愿意,可以将子查询作为永久视图,并在主查询中使用它:
CREATE VIEW score_tally AS
SELECT employer_id, SUM(score) AS total_score, COUNT(*) AS num_rows
FROM feedback
GROUP BY employer_id;
SELECT name, total_score/num_rows AS avg_score
FROM employers JOIN score_tally ON(employers.id = score_tally.employer_id)
WHERE avg_score > 0.5;
提示(再次):以上提示是愚蠢的,我们应该使用内置的AVG
:
CREATE VIEW score_tally AS
SELECT employer_id, AVG(score) AS avg_score
FROM feedback
GROUP BY employer_id;
SELECT name, avg_score
FROM employers JOIN score_tally ON(employers.id = score_tally.employer_id)
WHERE avg_score > 0.5;
让我们猜猜您的完整查询可能是什么样的:
SELECT job_id,
user_id,
title,
profiles.user_name AS user_name,
avg_score
FROM jobs
JOIN profiles ON(jobs.user_id = profiles.user_id)
JOIN job_categories ON(jobs.cat_id = job_categories.cat_id)
JOIN job_sub_categories ON(jobs.sub_cat_id = job_sub_categories.sub_cat_id)
JOIN (SELECT employer_id, AVG(score) AS avg_score FROM feedback GROUP BY employer_id) AS sq
ON(employers.id = sq.employer_id)
WHERE status = 'open' AND avg_score > 0.5
ORDER BY post_date desc
LIMIT 5