我想创建一个从 MySQL 数据库中获取图像数据的随机图像横幅。而且我只想随机获取最新的三条记录。
如何以随机顺序获取最近的 3 条记录?
我是以下查询:
SELECT * FROM bottom_advt WHERE bottom_advt_page_name='News' ORDER BY RAND() LIMIT 1
但它不起作用。
你说3条记录。所以试试:
SELECT * FROM bottom_advt WHERE bottom_advt_page_name='News' ORDER BY RAND() LIMIT 3
您将结果限制为LIMIT 1
. 将其更改LIMIT 3
为获得三个结果。
如果您想要最后三个记录之一,请尝试此操作:
SELECT * FROM bottom_advt WHERE bottom_advt_page_name='News' AND id+3>last_insert_id() ORDER BY RAND() LIMIT 1
你可以使用这个:
SELECT *
FROM bottom_advt
WHERE ID IN (SELECT * FROM (
SELECT id
FROM bottom_advt
WHERE bottom_advt_page_name='News'
ORDER BY id DESC
LIMIT 3) last)
ORDER BY RAND()
LIMIT 1
子查询将返回最后 3 个具有 id 的 id bottom_advt_page_name='News'
,而外部查询将随机选择其中一个。
请在此处查看小提琴。