这是我的代码
SELECT res.type,
res.contactname,
res.id,
res.inv_addressline2,
res.inv_addressline3,
res.signup_date,
res.engineer_id_global,
res.job_id_global,
res.neg_or_pos,
res.rating,
res.author_id_global,
res.timestamp_global,
res.short_description,
res.job_title,
res.feedback,
author_data.contactname AS `author_name`,
review_count.total_feedback,
review_count.total_rating
FROM (SELECT mb.type,
mb.contactname,
mb.id,
mb.inv_addressline2,
mb.inv_addressline3,
mb.signup_date,
fb.engineer_id AS `engineer_id_global`,
fb.timestamp AS `timestamp_global`,
fb.job_id AS `job_id_global`,
fb.neg_or_pos,
fb.rating,
fb.feedback,
fb.author_id AS `author_id_global`,
ac.engineer_id,
ac.timestamp,
ac.author_id,
jb.job_id,
SUBSTR(jb.job_description, 1, 200) AS `short_description`,
jb.job_title
FROM " . MEMBERS_TABLE . " AS mb
LEFT JOIN " . ACCEPTED . " AS ac
ON mb.id = ac.engineer_id
LEFT JOIN " . FEEDBACK . " AS fb
ON ac.job_id = fb.job_id
LEFT JOIN " . JOBS . " AS jb
ON fb.job_id = jb.job_id
WHERE mb.type = 2
ORDER BY
fb.timestamp DESC
) AS res
LEFT JOIN
(SELECT mb.id,
mb.contactname,
fb.author_id
FROM " . MEMBERS_TABLE . " AS mb
LEFT JOIN " . FEEDBACK . " AS fb
ON fb.author_id = mb.id
LIMIT 1
) AS `author_data`
ON res.author_id_global = author_data.author_id
LEFT JOIN
(SELECT COUNT(fb.engineer_id) AS `total_feedback`,
SUM(fb.rating) AS `total_rating`,
fb.engineer_id
FROM " . FEEDBACK . " AS fb
) AS `review_count`
ON res.engineer_id_global = review_count.engineer_id
GROUP BY res.contactname
ORDER BY res.contactname
我刚刚开始了解SQL。我担心的是第二个和第三个内部查询。我是否正确地说它将返回所有结果,因为没有where子句并使用“ON”语句返回结果或者是与初始查询结合的“ON”语句?< / p>
答案 0 :(得分:3)
此脚本存在许多问题:
" . MEMBERS_TABLE . "
," . ACCEPTED . "
等的表格。这些在MySQL中是不可接受的,MySQL通常使用反引号(`)来引用对象名称;如果要通过例如预处理此脚本。 Perl或Python,或者是另一种语言的更大脚本的一部分,这样说会很有帮助。order by
子句,没有明显的原因。这可以删除。id
唯一标识MEMBERS_TABLE上的记录,则可以完全删除子查询,并将其替换为res.author_id_global = MEMBERS_TABLE.id
上的MEMBERS_TABLE单个左连接。不需要limit
条款。id
无法唯一标识MEMBERS_TABLE上的记录,则应将子查询重写为select distinct id, contact_name FROM " . MEMBERS_TABLE . " AS mb where res.author_id_global = mb.id LIMIT 1
。如果同一id
有多个匹配作者,则会随机选择一个。where
条款 - 它将在子查询中由工程师汇总所有工程师的反馈和评级,然后每个工程师将从其他工程师链接到相应的工程师来自on
子句的left join
条件的数据集。答案 1 :(得分:0)
第二个内部查询有限制1.只有一个条件只显示一个结果。第三个内部查询没有任何问题。