SQL 查询选择除最大值之外的所有内容
我有一个相当复杂的查询,它从三个表中获取数据,现在我希望它变得更加复杂(天哪)!
我希望最后发布的功能显示在页面的它自己的部分中,通过选择表中的最后一个条目非常容易。 但是,对于复杂的查询(网站的主页),我希望能够不显示此功能。
我想将以下查询联合
到我之前的查询,但它没有返回正确的结果:
SELECT
features.featureTitle AS title,
features.featureSummary AS body,
features.postedOn AS dummy,
DATE_FORMAT( features.postedOn, '%M %d, %Y' ) AS posted,
NULL,
NULL,
staff.staffName,
features.featureID
FROM
features
LEFT JOIN staff ON
features.staffID = staff.staffID
WHERE features.postedOn != MAX(features.postedOn)
ORDER BY dummy DESC LIMIT 0,15
此查询返回以下错误:
MySQL 错误:#1111 - 组函数的使用无效
有没有办法解决这个问题?
I have this rather complex query that grabs data from three tables, and now I want it to be even more complicated (Oh dear)!
I'd like the last posted feature to be displayed in it's own section of the page, and that's pretty easy by selecting the last entry in the table. However, for the complex query (the main page of the site), I'd like to be able to NOT have this feature displayed.
I'd like to union
the following query to my previous query, but it isn't returning the correct results:
SELECT
features.featureTitle AS title,
features.featureSummary AS body,
features.postedOn AS dummy,
DATE_FORMAT( features.postedOn, '%M %d, %Y' ) AS posted,
NULL,
NULL,
staff.staffName,
features.featureID
FROM
features
LEFT JOIN staff ON
features.staffID = staff.staffID
WHERE features.postedOn != MAX(features.postedOn)
ORDER BY dummy DESC LIMIT 0,15
This query returns the following error:
MySQL error: #1111 - Invalid use of group function
Is there any way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
max
查询需要位于其自己的子查询中,因此最终的 SQL 应该是:The
max
query needs to be in its own subquery, so your final SQL should be::您遇到的问题是,您需要在遍历每一行时从表中找到最大(最新)功能,但 MAX() 是一个组函数 - 您必须对所有行进行分组才能使用它。
您可以使用子选择来获取最后一个特征的 id:
这种方法有一个问题 - 子选择针对每一行运行,但它并不那么昂贵。
the problem you have is that is that you need to find the max (latest) feature from the table, while going over each row, but MAX() is a group function - you have to group all rows to use it.
you can use a sub-select to get the id of the last feature:
there is a problem with this approach - the subselect is run for every row, but it is not that expensive.
您还可以按 PostedOn 字段降序排序并添加 OFFSET 1,这将从第二行开始显示结果。
You could also order by the PostedOn field in descending order and add OFFSET 1, which will display your results starting from the second row.