[英]Get next and previous records sorting by non-unique field
我在閱讀類似問題時找不到答案,因此我將在此處提出問題,感謝您對此問題的任何幫助。
在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個網頁:
按日期排序的所有活動文章的列表(重要:幾篇文章可能具有相同的日期)。 這工作正常,這里沒有問題。
單篇文章閱讀頁面,另外,該頁面上還有“下一個”和“上一個”鏈接。 這是一個問題。
我想將“ next”和“ prev”鏈接顯示為href =“ article.php?id = 8”。 所以我想根據這樣的查詢從數據庫中獲取下一個記錄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條記錄(標識:14和13),因為它們具有相同的日期。 我嘗試使用不同的查詢,但是所有結果都不是100%正確(在某些情況下,它總是返回相同的數字,例如:5、6、14、6、14 .....等)
是否可以通過MySQL查詢基於當前ID和所需順序獲取“下一個” ID? 我不反對做幾個查詢或使用嵌套查詢。
作為一種解決方法,我當然可以檢索所有id的有序數組,如下所示:
SELECT id FROM articles WHERE isactive=1 ORDER BY date
然后使用此數組定義“下一個”和“上一個”,但是我不喜歡這種解決方案。 如果您可以指出一些類似的主題或其他可能的解決方法,請這樣做。 謝謝。
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)
為什么這樣做,為什么不使用
從新聞中選擇ID依日期排序ASC LIMIT 6,1-位置,計數
如果使用SQL查詢緩存,則速度可能會更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.