我有以下表格结构:
id |name |date
1 a 2012-01-01
2 a 2011-01-01
3 a 2010-01-01
4 a 2014-01-01
5 a 2011-01-01
我希望按日期执行选择顺序(desc),然后从结果中选择前3行,条件是id = 1.所以查询的第二部分将是"给我从id等于1"
的行开始的前3行 修改
在第一个"部分"结果将是:
SELECT id, name, date FROM table ORDER BY date DESC
id |name |date
4 a 2014-01-01
1 a 2012-01-01
2 a 2011-01-01
5 a 2011-01-01
3 a 2010-01-01
在第二部分之后它应该是这样的(所以在id为1的行之后的前3个):
id |name |date
2 a 2011-01-01
5 a 2011-01-01
3 a 2010-01-01
我不知道如何解决它,请帮助我。
修改 这是我想重写的具体代码:
SELECT `id`, `questions`.`userid`, `categories`.`name`, `user`.`username`, `title`,
`details`, `date` FROM `questions`
LEFT JOIN `user`
ON `questions`.`userid` = `user`.`userid`
LEFT JOIN `categories`
ON `questions`.`categoryid` = `categories`.`categoryid`
ORDER BY `date` DESC LIMIT 10
答案 0 :(得分:1)
这并不漂亮,因为MySQL不支持row_number()
或公用表表达式,但它应该有效。基本上,获取按日期排序的行号,然后选择行号大于任意值的行号(在本例中为1)。最后使用limit
选择所需的记录数。
SELECT id, name, mydate
FROM (
SELECT id, name, mydate, @rn:=@rn+1 rn
FROM mytable, (select @rn:=0) t
ORDER BY mydate DESC
) t2
WHERE rn > (
select rn
from (
SELECT id, name, mydate, @rn:=@rn+1 rn
FROM mytable, (select @rn:=0) t
ORDER BY mydate DESC
) t2
where id = 1
)
LIMIT 3
答案 1 :(得分:1)
这是你想要做的......如果找到第一个id等于4然后选择那个。然后限制偏移量以转到下一行并拉出3
SELECT id, name, m_date from(
SELECT id, name, m_date, @a := id, if(@a = 4, @b := 1, @b) AS join_id
FROM test
join(SELECT @a := 0, @b := 0) t
ORDER BY m_date DESC
) AS tt
WHERE join_id = 1
LIMIT 1,3
SELECT temp.`id`, temp.`userid`, `categories`.`name`, `user`.`username`, temp.`title`,
temp.`details`, temp.`date` FROM (
SELECT `id`, `categoryid`, `details`, `title`, `userid`, `date`, @a := id, if(@a = 11, @b := 1, @b) AS join_id
FROM `questions`
join(SELECT @a := 0, @b := 0) t
ORDER BY `date` DESC
) as temp
LEFT JOIN `user`
ON temp.`userid` = `user`.`userid`
LEFT JOIN `categories`
ON temp.`categoryid` = `categories`.`categoryid`
WHERE join_id = 1
LIMIT 1,10;
SEE FIDDLE需要澄清
答案 2 :(得分:1)
SELECT *
FROM table
WHERE date < (SELECT date FROM table WHERE id = 1)
ORDER BY date DESC
LIMIT 3