问题标题几乎总结了它。
我正在加入两个表,其结果是按时间戳列排序的,&按升序排序(因此最近的行位于底部)。在这种情况下如何获得最后20行?
代码(假设两个表是表A和表B):
SELECT A.*, B.some_column
FROM A
INNER JOIN B ON B.id = A.id AND (other conditions here)
ORDER BY A.timestamp ASC
LIMIT 20
目前返回前20行。我需要最后20个。
P.S。我需要将最终结果集按ASCENDING顺序排序。最近的行需要在最后,而不是开头!
答案 0 :(得分:1)
如果您想在查询中通过ASC订购,您可以:
SELECT A.*, B.some_column
FROM A
INNER JOIN B ON B.id = A.id
WHERE id IN (SELECT * FROM (
SELECT id FROM A ORDER BY timestamp DESC LIMIT 20
) AS s) ORDER BY A.timestamp ASC
答案 1 :(得分:1)
试试这个
SELECT * FROM
(
SELECT A.*, B.some_column
FROM A
INNER JOIN B ON B.id = A.id AND (other conditions here)
ORDER BY A.timestamp Desc
LIMIT 20
) Temp
ORDER BY A.timestamp ASC
答案 2 :(得分:1)
SELECT * FROM (
SELECT A.*, B.some_column
FROM A
INNER JOIN B ON B.id = A.id AND (other conditions here)
ORDER BY A.timestamp DESC
LIMIT 20
) AS RESULT
ORDER BY RESULT.timestamp ASC
答案 3 :(得分:0)
反转结果的顺序,
在SQL Server中,使用:
select top 20 ...
在MySQL中,使用:
select ... order by num desc limit 20
答案 4 :(得分:0)
首先,按另一种方式排序:
ORDER BY `timestamp` DESC
LIMIT 0,20