我试过这个
select posts.id, posts.title
from posts
inner join (
select post_id,max(created)
from comments
group by post_id
order by max(created) DESC ) as foo
on posts.id=foo.post_id
order by foo.max(created) DESC;
错误
ERROR 1630 (42000): FUNCTION foo.max does not exist.
Check the 'Function Name Parsing and Resolution' section in the Reference Manual
表
mysql> describe comments;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| post_id | int(11) | NO | MUL | NULL | |
| name | varchar(255) | NO | | NULL | |
| email | varchar(255) | NO | | NULL | |
| body | varchar(500) | NO | | NULL | |
| mark | tinyint(4) | NO | | 1 | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
mysql> describe posts;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | | NULL | |
| title | varchar(255) | NO | | NULL | |
| body | text | YES | | NULL | |
| category_id | int(11) | NO | | NULL | |
| tags | varchar(50) | NO | | NULL | |
| mark | tinyint(4) | NO | | 1 | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)
我需要发布最新评论的帖子。
答案 0 :(得分:3)
您在此处使用了错误的引用: -
foo.max(created)
应该是: -
max(foo.created)
错误信息已经显示出问题在哪里,
您应该在遇到错误时始终调试错误消息
但是你没有返回为别名foo创建的列,所以: -
select posts.id, posts.title
from posts
inner join
(
select post_id,max(created) AS created
from comments
group by post_id
) as foo
on posts.id=foo.post_id
order by created DESC; <-- you don't need max
答案 1 :(得分:1)
没有foo.max
功能。
你的意思是:
SELECT posts.id,
posts.title
FROM posts
INNER JOIN (SELECT post_id,
created
FROM comments
GROUP BY post_id
ORDER BY Max(created) DESC) AS foo
ON posts.id = foo.post_id
ORDER BY Max(foo.created) DESC;
答案 2 :(得分:1)
select posts.id, posts.title
from posts
inner join (
select post_id, max(created) as most_recent
from comments
group by post_id) as foo
on posts.id=foo.post_id
order by most_recent DESC;
问题是子查询中的max(created)
应该有一个名称。您不需要在子查询中进行排序。