用于按日期提取帖子的MySQL查询逻辑

时间:2011-12-26 19:20:15

标签: php mysql logic

任何人都可以提供有关执行以下操作的MySQL查询中逻辑的建议:

  • 选择至少100个帖子
  • 选择上个月加载的想法中的所有帖子,例如,如果100个帖子在9月中旬加载帖子,则应加载9月整个月的帖子,而不是在中途切断。

不幸的是,第二个选项并不是我所知道的甚至可以用于MySQL,所以我正在寻求一些帮助。

干杯。

2 个答案:

答案 0 :(得分:1)

只计算子查询中第100行的月份并使用BETWEEN条件中的值

你基本上需要什么:

  • 找到第100行的日期(date_a)
  • 找到date_a(date_b)
  • 的月份的第一天
  • 查找比date_b
  • 更新的所有行

因此,

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,重要列为ThoughtIDThoughtTime。显然,您需要根据需要进行自定义:

SQL Server:

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

mySQL(未经测试,需要改进):

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用户可以看看。