我需要以ASC顺序检索最后3行,所以这是最终查询:
SELECT c.comment_id,c.comment_message,c.comment_date,u.user_id,u.first_name,u.last_name,p.profile_picture_path
FROM
(SELECT c.comment_id,c.comment_message,c.comment_date,u.user_id,u.first_name,u.last_name,p.profile_picture_path
FROM posts_comments c,users u,users_profile_pictures p
WHERE c.user_id = u.user_id AND u.user_id = p.user_id AND c.post_id = '82'
ORDER BY c.comment_date DESC
LIMIT 3)
ORDER BY c.comment_date ASC
我知道这里有问题,我收到了这个错误:Every derived table must have its own alias
。如何通过相应的表指出Select语句中的列?意思是,如何选择c.comment_id
?
答案 0 :(得分:4)
SELECT comment_id,
comment_message,
comment_date,
user_id,
first_name,
last_name,
profile_picture_path
FROM (
SELECT c.comment_id,
c.comment_message,
c.comment_date,
u.user_id,
u.first_name,
u.last_name,
p.profile_picture_path
FROM posts_comments c,
users u,
users_profile_pictures p
WHERE c.user_id = u.user_id
AND u.user_id = p.user_id
AND c.post_id = '82'
ORDER BY c.comment_date DESC
LIMIT 3
) subA -- <<== put alias here
-- the purpose of the alias is to supply an identification
-- for the subquery
ORDER BY comment_date ASC
答案 1 :(得分:1)
SELECT x.comment_id
, x.comment_message
, x.comment_date
, x.user_id
, x.first_name
, x.last_name
, x.profile_picture_path
FROM
( SELECT c.comment_id
, c.comment_message
, c.comment_date
, u.user_id
, u.first_name
, u.last_name
, p.profile_picture_path
FROM posts_comments c
JOIN users u
ON u.user_id = c.user_id
JOIN users_profile_pictures p
ON p.user_id = u.user_id
WHERE c.post_id = 82
ORDER
BY c.comment_date DESC
LIMIT 3
) x
ORDER
BY x.comment_date ASC;