在阅读类似问题时我无法找到答案,所以我在这里提出我的问题,感谢您对此事的任何帮助。
在MySQL DB中有一个包含文章的表:
id date is_active title text
3 2017-01-20 1 New payment system goes live some articl
5 2017-01-21 1 Library v.2.5 released some articl
6 2017-01-22 1 New skins and themes some articl
7 2017-01-25 0 Terms and Conditions updated some articl
8 2017-01-26 1 Don't forget to subscribe some articl
10 2017-01-22 0 Support Chat beta release some articl
11 2017-01-30 1 Maintenance window next Sunday some articl
12 2017-01-28 1 Refer a friend and get a bonus some articl
13 2017-01-26 1 Follow us in social networks some articl
14 2017-01-22 1 Video sharing feature is now live some articl
我有2个网页:
按日期排序的所有活动文章的列表(重要:多篇文章可能具有相同的日期)。 这很好,这里没问题。
单篇文章阅读页面,另外我有"下一页"和"以前"该页面上的链接 这是一个问题。
我想展示下一个'和' prev'链接为href =" article.php?id = 8"。所以我想根据这样的查询从DB获取下一个记录ID:
SELECT id FROM articles WHERE date > (SELECT date FROM news WHERE id = 6) and isactive = 1 ORDER BY date ASC LIMIT 1;
但是,在定义具有相同日期的下一篇文章ID时,我的查询无法正常工作。当用户停留在文章ID = 3并点击“下一步”时多次我会期望以下加载文章的顺序:
id title date is_active
5 Library v.2 2017-01-21 1
6 New skins a 2017-01-22 1
14 Video shari 2017-01-22 1
8 Don't forge 2017-01-26 1
13 Follow us i 2017-01-26 1
12 Refer a fri 2017-01-28 1
11 Maintenance 2017-01-30 1
但我得到的是:5,6,8,12,11。因此,这个序列中缺少2条记录(ID:14和13),因为它们具有相同的日期。 我尝试使用不同的查询,但所有结果都不是100%正确(在某些情况下,它会保持返回相同的数字,例如:5,6,14,6,14 ......等)
是否有可能获得下一个'通过MySQL查询基于当前ID和所需顺序的ID?我并不反对进行多次查询或使用嵌套查询。
作为一种解决方法,我当然可以检索所有ID的有序数组,如下所示:
SELECT id FROM articles WHERE isactive=1 ORDER BY date
然后定义' next'和之前的'使用这个数组,但我不喜欢这个解决方案。 如果您能指出一些类似的主题或其他可能的方法来解决这个问题,请做。 谢谢。
答案 0 :(得分:0)
SELECT id
FROM articles
WHERE date >= (SELECT date -- changed
FROM news
WHERE id = 6)
AND isactive = 1
AND id NOT IN(6) -- added, maybe id!=6 or id<>6
ORDER BY date ASC
LIMIT 1
-- (all id date >= date) - (id=6)
为什么要这样做,为什么不使用
SELECT id FROM news ORDER BY date ASC LIMIT 6,1 - possition,count
如果是SQL查询缓存,这可能会更快。