如何最小化我的查询?

时间:2011-03-21 10:26:00

标签: php mysql sql

我想最小化我的查询

 "SELECT * FROM tb_videos  GROUP BY DATE(added) ORDER BY DATE(added) desc"
获得结果后

foreach($result as $rst)
{    
  $dt=date('Y-m-d',strtotime($rst->added));
  SELECT * FROM tb_videos WHERE  DATE(added)='$dt' ORDER BY added desc
}

我可以使用单一查询吗?

3 个答案:

答案 0 :(得分:2)

您的查询毫无意义。首先,您要从数据中选择DISTINCT日期(忽略时间)。然后,对于每个日期,您..选择该日期的所有数据?

为什么不点一个查询

SELECT *, DATE(added) as DateNoTime
FROM tb_videos
ORDER BY added desc

如果您只想要5个日期,并且表格很大,则有两种可能性。

1,日期中从不存在空白,您可以使用

SELECT *, DATE(added) as DateNoTime
FROM tb_videos
WHERE added >= ADDDATE(CURDATE(), interval -4 days)
ORDER BY added desc

2,如果可能存在间隙,例如昨天什么都没有,所以它必须显示最近5天有记录

SELECT *, DATE(added) as DateNoTime
FROM (
    select min(DateNoTime) as MinDate
    from
    (
        select DATE(added) as DateNoTime
        FROM tb_videos
        order by DateNoTime desc
        limit 5
    ) x) y, tb_videos
WHERE added >= y.MinDate
ORDER BY added desc

这为您提供了所有数据。在PHP中,跟踪DateNoTime。每当更改时,您处于不同的日期,之前会导致您触发另一个查询。否则代码只会发生微小变化。

未经检查的PHP代码

$result = mysql_query('
    SELECT *, DATE(added) as DateNoTime
    FROM (
        select min(DateNoTime) as MinDate
        from
        (
            select DATE(added) as DateNoTime
            FROM tb_videos
            order by DateNoTime desc
            limit 5
        ) x) y, tb_videos
    WHERE added >= y.MinDate
    ORDER BY added desc
');
$prevdate = NULL;
foreach($result as $rst)
{    
    if($prevdate!=$rst=>DateNoTime) {
        // do something, like printing out a header for each new date
        $prevdate=$rst=>DateNoTime;
    }

    // do something with the record
}

答案 1 :(得分:1)

您想最小化找到的记录吗?使用where子句来选择您的特定记录

“SELECT * FROM tb_videos WHERE videogroup = action GROUP BY DATE(已添加)ORDER BY DATE(已添加)desc”

例如

答案 2 :(得分:0)

SELECT * FROM tb_videos WHERE DATE(added) = curdate() ORDER BY added desc