我快要把头发拉过这个了。这是我正在使用的查询:
SELECT
*,
GROUP_CONCAT(DISTINCT d.title SEPARATOR ', ') AS departments,
MAX(d.department_id) AS department_id,
CONCAT(friendly_last_name, ', ', friendly_first_name) AS professor_name,
IF( p.reviews = 0, "", p.quality ) AS quality,
IF( p.reviews = 0, "", p.reviews ) AS reviews,
IF( p.reviews = 0, "", p.ease ) AS ease,
u.url
FROM
educational.professors_departments
LEFT JOIN educational.professors p USING (professor_id)
LEFT JOIN educational.departments d USING (department_id)
LEFT JOIN educational.universities u ON (p.university_id = u.university_id)
WHERE
p.university_id = 3231
AND d.department_id IN ('91')
GROUP BY
professor_id
ORDER BY p.friendly_last_name ASC, p.friendly_first_name ASC
当我按原样运行该查询时,我得到101个结果。如果我在查询的末尾添加一个简单的LIMIT 20,那么查询会突然返回一个结果。
好像这不够奇怪,如果我将LIMIT 20更改为LIMIT 25,我会收到25个结果。有什么神奇的东西我对此缺失了吗?我不能为我的生活弄明白。
P.S。 - 我尝试过SQL_NO_CACHE无济于事。 P.P.S. - 如果我删除整个ORDER BY子句,但是保留LIMIT 20 ......我得到20个结果
答案 0 :(得分:2)
我只能猜测引擎正在尽力猜测一些元素......你已经离开了我不相信你真正想要的联接...只是NORMAL加入...我会先尝试一下解析您的查询并查看它可能会显示有关索引,全表扫描等的洞察力......
此外,使用select *通常是糟糕且懒惰的查询。获取您想要和期望的列。如果一个结构发生了变化并且你依赖于*,那么将来你可能无法预见到它。
我将重组如下,查看结果并检查ITs EXPLAIN
SELECT STRAIGHT_JOIN
p.Professor_ID,
CONCAT(p.friendly_last_name, ', ', p.friendly_first_name) AS professor_name,
GROUP_CONCAT(DISTINCT d.title SEPARATOR ', ') AS departments,
MAX(d.department_id) AS department_id,
IF( p.reviews = 0, "", p.quality ) AS quality,
IF( p.reviews = 0, "", p.reviews ) AS reviews,
IF( p.reviews = 0, "", p.ease ) AS ease,
u.url
FROM
educational.professors p
JOIN educational.professors_departments pd
on p.Professor_ID = pd.Professor_ID
JOIN educational.departments d
on pd.Department_ID = d.Department_ID
AND d.department_id IN ('91')
JOIN educational.universities u
ON p.university_id = u.university_id
WHERE
p.university_id = 3231
GROUP BY
p.professor_id
ORDER BY
p.friendly_last_name ASC,
p.friendly_first_name ASC
LIMIT 20
查看你的IF()条款的质量,评论,轻松......你是否故意仅在所有3个元素的p.Reviews = 0时获取这些值...或者它们是否应该代表值的每一列...