ORDER BY is being ignored in subquery join?(ORDER BY 在子查询连接中被忽略?)
问题描述
我有 3 个表:用户、项目和文件.以下是相关栏目:
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
我认为 ORDER BY filecreated DESC 会解决这个问题,但它似乎完全被忽略了.
I would think ORDER BY filecreated DESC would solve this, but it seems completely ignored.
我对 SQL 还很陌生,也许我的方法不对?
I'm fairly new to SQL, perhaps I'm not approaching this the right way?
推荐答案
你的问题在这里,在你的子查询中:
Your problem is here, in your subquery:
(SELECT filename,projectid FROM files
GROUP BY files.projectid
ORDER BY filecreated DESC) AS f
由于您使用的是那种混合分组和非分组列,我假设您使用的是 MySQL.请记住,在应用 GROUP BY
子句后,ORDER BY
子句将有 no effect - 你不能相信 MySQL 允许这样的语法(一般来说,在普通 SQL 中,这根本就是不正确的查询).
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
这篇关于ORDER BY 在子查询连接中被忽略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ORDER BY 在子查询连接中被忽略?
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01