Is this a MySQL bug or am I going insane? Query not returning enough results
I am near the point of pulling my hair out over this one. This is the query I am working with:
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
When I run that query as is, I get 101 re开发者_如何学Csults. If I add a simple LIMIT 20 to the end of the query, all of the sudden the query returns one result.
As if that's not weird enough, if I change LIMIT 20 to LIMIT 25, I receive 25 results. Is there some magical thing that I'm missing about this? I can not for the life of me figure it out.
P.S. - I have tried SQL_NO_CACHE to no avail. P.P.S. - If I remove the entire ORDER BY clause, but leave LIMIT 20...I get 20 results
I can only guess the engine is doing its best to guess on some elements... you have left joins which I don't believe is what you really want... just NORMAL joins... I would first try an EXPLAIN on your query and see what it comes up with that might show insight with indexes, full table scans, etc...
Additionally, using a select * is typically bad and lazy querying. Get the columns you want and expect. If a structure ever changes and you rely on *, you could get hosed unforeseen in the future.
I would restructure as follows, see results and check 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
Looking at your IF() clauses for quality, reviews, ease... were you intentionally only getting those values ONLY when p.Reviews = 0 for all 3 elements... or should they be representing each column of a value...
精彩评论