任何人都可以提供有关执行以下操作的MySQL查询中逻辑的建议:
不幸的是,第二个选项并不是我所知道的甚至可以用于MySQL,所以我正在寻求一些帮助。
干杯。
答案 0 :(得分:1)
只计算子查询中第100行的月份并使用BETWEEN条件中的值
你基本上需要什么:
因此,
SELECT created as date_a
FROM posts
ORDER BY created DESC
LIMIT 99, 1
SELECT
(LAST_DAY(created) + INTERVAL 1 DAY - INTERVAL 1 MONTH) as date_b
FROM posts
ORDER BY created DESC
LIMIT 99, 1
后者用作子查询的最后一个查询是你的作业=)
答案 1 :(得分:0)
我开发了一个在SQL Server中运行的答案,然后才意识到您正在寻找特定于mySQL的解决方案。但是,我没有访问mySQL实例来验证语法 - 我确信它仍然没有被破坏,但它确实接近它应该是什么。我很确定searchDate连接失败,因此假设语法已得到纠正,将返回意外结果。
此解决方案假设您的源表名为thoughts
,重要列为ThoughtID
和ThoughtTime
。显然,您需要根据需要进行自定义:
DECLARE @Results TABLE (
ThoughtID int,
ThoughtTime datetime)
DECLARE @date date
DECLARE @minResults int
DECLARE @totResults int
SET @minResults = 100
SET @totResults = (SELECT COUNT(1) FROM thougts)
SET @date = CONVERT(CHAR(4), YEAR(GETDATE()), 100) + '-' + CONVERT(CHAR(2), MONTH(GETDATE()),120) + '-01'
IF @totResults <= @minResults
BEGIN
-- Not enough results, grab everything
SELECT ThoughtID, ThoughtTime
FROM thougts
ORDER BY ThoughtTime DESC
END ELSE
BEGIN
WHILE (SELECT COUNT(1) FROM @Results) < @minResults
BEGIN
DELETE FROM @Results -- Can be optimized
SET @date = DATEADD(m, -1, @date)
INSERT INTO @Results (ThoughtID, ThoughtTime) (
SELECT ThoughtID, ThoughtTime
FROM thougts
WHERE ThoughtTime >= @date)
END
SELECT *
FROM @Results
ORDER BY ThoughtTime DESC
END
CREATE PROCEDURE TEST()
BEGIN
CREATE TEMPORARY TABLE Results (
ThoughtID int,
ThoughtTime datetime);
DECLARE searchDate date;
DECLARE minResults int;
DECLARE totResults int;
SET minResults = 100;
SET totResults = (SELECT COUNT(1) FROM thougts);
SET searchDate = CONVERT(YEAR(CURRENT_TIMESTAMP()), CHAR(4)) + '-' + CONVERT(MONTH(CURRENT_TIMESTAMP()), CHAR(2)) + '-01';
IF totResults <= minResults
THEN
SELECT ThoughtID, ThoughtTime
FROM thougts
ORDER BY ThoughtTime DESC;
ELSE
WHILE (SELECT COUNT(1) FROM Results) < minResults DO
DELETE FROM Results; -- Can probably be optimized
SET searchDate = DATE_SUB(searchDate, INTERVAL 1 MONTH);
INSERT INTO Results (ThoughtID, ThoughtTime) (
SELECT ThoughtID, ThoughtTime
FROM thougts
WHERE ThoughtTime >= searchDate);
END WHILE;
SELECT *
FROM Results
ORDER BY ThoughtTime DESC;
END IF;
)
END
如果我在接下来的几天内访问mySQL实例,我会尝试更多地清理它。否则,希望另一个SO用户可以看看。