MySQL WHERE 時間戳 >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY) (MySQL WHERE timestamp >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY))


問題描述

MySQL WHERE 時間戳 >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY) (MySQL WHERE timestamp >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY))

What's the best way to express this in one SQL query?

"Select a few random items that fall within x days of the newest item in the table."

I tried the following:

SELECT *
FROM table
HAVING `timestamp` >= SUBDATE(MAX(`timestamp`), INTERVAL 5 DAY)
ORDER BY RAND()
LIMIT 10

But this only gives me a single result, not 10. WHERE instead of HAVING doesn't cut it because of the use of MAX().


參考解法

方法 1:

You probably want your MAX statement in a sub-query:

SELECT *
FROM table
WHERE `timestamp` >= SUBDATE((SELECT MAX(`timestamp`) FROM table), INTERVAL 5 DAY)
ORDER BY RAND()
LIMIT 10

方法 2:

SELECT *
FROM table
where `timestamp` >= (select SUBDATE(MAX(`timestamp`), INTERVAL 5 DAY) from table )
ORDER BY RAND()
LIMIT 10;

(by decezeBlixtZA.)

參考文件

  1. MySQL WHERE timestamp >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY) (CC BY-SA 3.0/4.0)

#Date #MySQL






相關問題

MySQL WHERE 時間戳 >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY) (MySQL WHERE timestamp >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY))

需要有關排序要求的幫助 (Need assistance with a usort requirement)

在 Java 日期/日曆對像中發現神秘的毫秒數 (Mysterious milliseconds number found in Java Date/Calendar object)

按日期子集 data.frame (Subset data.frame by date)

根據添加到頁面的內容更改 div 類 (change div class based on content added to page)

我應該如何設置日期? (How should I set the date?)

日期的 Drupal 8 上下文過濾器 (Drupal 8 contextual filter for date)

是什麼導致了這個無效的日期錯誤? (What is causing this invalid date error?)

按存儲在文本列中的日期排序表 (Order table by date stored in text column)

如何啟用靜態時間但仍有動態日期? (How do I enable a static time but still have dynamic date?)

是否可以在日期列中加載各種格式的數據?甲骨文 (is that possible to load data of various format in date column | Oracle)

MongoDB/Mongoose 時區日期遞減問題 (MongoDB/Mongoose timezone date decrement problem)







留言討論