问题
I have 3 tables: users, projects, and files. Here's the relevant columns:
users: [userid](int)
projects: [userid](int) [projectid](int) [modified](datetime)
files: [userid](int) [projectid](int) [fileid](int) [filecreated](datetime)
I'm using a query to list all projects, but I also want to include the most recent file from another table. My approach to this was using a subquery to join on.
Here's what I came up with, but my problem is that it's returning the oldest file:
SELECT * FROM projects
INNER JOIN users ON projects.userid = users.userid
JOIN (SELECT filename,projectid FROM files
GROUP BY files.projectid
ORDER BY filecreated DESC) AS f
ON projects.projectid = f.projectid
ORDER BY modified DESC
I would think ORDER BY filecreated DESC would solve this, but it seems completely ignored.
I'm fairly new to SQL, perhaps I'm not approaching this the right way?
回答1:
Your problem is here, in your subquery:
(SELECT filename,projectid FROM files
GROUP BY files.projectid
ORDER BY filecreated DESC) AS f
since you're using that kind of mixing grouped and non-grouped columns I assume you're using MySQL. Remember, ORDER BY
clause will have no effect after applying GROUP BY
clause - you can not rely on the fact, that MySQL allows such syntax (in general, in normal SQL this is incorrect query at all).
To fix that you need to get properly formed records in your subquery. That could be done, for example:
SELECT
files.filename,
files.projectid
FROM
(SELECT
MAX(filecreated) AS max_date,
projectid
FROM
files
GROUP BY
projectid) AS files_dates
LEFT JOIN
files
ON files_dates.max_date=files.filecreated AND files_dates.projectid=files.projectid
回答2:
I assume you want a list of projects with the latest file and the user that created it:
SELECT projects.projectid, f.username, f.filename, f.filecreated
FROM projects
LEFT OUTER JOIN (
SELECT TOP 1 username, filename, filecreated
FROM files
INNER JOIN users ON users.userid = files.userid
ORDER BY filecreated DESC
) AS f ON projects.projectid = f.projectid
ORDER BY modified DESC
来源:https://stackoverflow.com/questions/18481867/order-by-is-being-ignored-in-subquery-join