无法在 Union 查询中使用 order by
Not able to use order by in Union query
我有以下原始 mysql 查询
select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r LEFT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = ?
UNION
select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r RIGHT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = ?
我正在尝试添加排序依据,以便我可以按日期对数据进行排序,但出现以下错误
#1250 - Table 'rp' from one of the SELECTs cannot be used in ORDER clause
下面是修改后的查询:
(select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r LEFT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = 46)
UNION
(select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r RIGHT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = 46) order by rp.DateCreated desc
如果您从 ORDER BY
子句中删除别名,您的最后一个查询应该有效:
(SELECT *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated
FROM review r
LEFT JOIN reviewphoto rp ON r.ReviewId = rp.ReviewId
WHERE r.DishId = 46)
UNION
(SELECT *, r.ReviewId, r.DateCreated
FROM review r
RIGHT JOIN reviewphoto rp ON r.ReviewId = rp.ReviewId
WHERE r.DishId = 46)
ORDER BY ActualDateCreated DESC;
我有以下原始 mysql 查询
select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r LEFT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = ?
UNION
select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r RIGHT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = ?
我正在尝试添加排序依据,以便我可以按日期对数据进行排序,但出现以下错误
#1250 - Table 'rp' from one of the SELECTs cannot be used in ORDER clause
下面是修改后的查询:
(select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r LEFT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = 46)
UNION
(select *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated from review r RIGHT join reviewphoto rp ON r.ReviewId = rp.ReviewId where r.DishId = 46) order by rp.DateCreated desc
如果您从 ORDER BY
子句中删除别名,您的最后一个查询应该有效:
(SELECT *, r.ReviewId AS ActualReviewId, r.DateCreated AS ActualDateCreated
FROM review r
LEFT JOIN reviewphoto rp ON r.ReviewId = rp.ReviewId
WHERE r.DishId = 46)
UNION
(SELECT *, r.ReviewId, r.DateCreated
FROM review r
RIGHT JOIN reviewphoto rp ON r.ReviewId = rp.ReviewId
WHERE r.DishId = 46)
ORDER BY ActualDateCreated DESC;