我的数据库中有这个表
categoriesSupports-> id,category_id,support_id,date
问题是我需要提取所有support_id,其中date是从现在起最近的日期......
这样的东西......如果在数据库表中有
id, category_id, support_id, date
1 1 1 2010-11-23
2 1 2 2010-11-25
3 1 1 2010-11-26
4 1 3 2010-11-24
我需要得到
id, category_id, support_id, date
2 1 2 2010-11-25
3 1 1 2010-11-26
4 1 3 2010-11-24
所以为了更好的未定......我需要最近的日期 每个支持,我只有过去的日期... 我正在尝试很多,我不知道如何......
答案 0 :(得分:2)
以下内容应该给你:
未来的一个类别支持(如果存在)
(
SELECT *
FROM `categoriesSupports`
WHERE `date` < CURDATE()
ORDER BY `date` DESC
LIMIT 1
)
UNION
(
SELECT *
FROM `categoriesSupports`
WHERE `date` = CURDATE()
)
UNION
(
SELECT *
FROM `categoriesSupports`
WHERE `date` > CURDATE()
ORDER BY `date` ASC
LIMIT 1
)
答案 1 :(得分:1)
SELECT *
FROM `categoriesSupports`
WHERE `date` IN (
SELECT `date`
FROM `categoriesSupports`
ORDER BY `date` DESC
LIMIT 1
)
注意:
LIMIT n
以选择更多日期的条目。 IN
替换为=
,因为子选择只会返回一个值。 ORDER BY date DESC
替换为ORDER BY ABS(NOW() - date) ASC
。 使用JOINS的解决方案。仅在您有过去的日期时才会工作。
SELECT a.*
FROM `categoriesSupports` AS a
LEFT JOIN `categoriesSupports` AS b
ON b.date > a.date
WHERE b.id IS NULL
仅供参考。
SELECT *
FROM `categoriesSupports`
WHERE DATEDIFF(NOW(), `date`) < 3
如果您想要更多或更少的天数,请将3
替换为任意数字。
SELECT a.*
FROM `categoriesSupports` AS a
LEFT JOIN `categoriesSupports` AS b
ON b.support_id = a.support_id AND b.date > a.date
WHERE b.id IS NULL
这回答了问题的最新版本。
答案 2 :(得分:0)
SELECT *
FROM CurrentDeals
WHERE (julianday(Date('now')) - julianday(date))<=3
ORDER BY date ASC
在这里,您必须决定“最接近”的含义。我用3作为样本。这将列出记录,其日期值小于或等于3.
希望这是你想要的。