如何优化这些查询?

时间:2009-09-02 13:23:02

标签: php sql mysql math

请考虑以下代码段:

$beat = date('B'); // 1 beat = 86.4 seconds, 1000 beats = 1 day
$total = 'SELECT COUNT(id) FROM ads WHERE featured = 1;'; // number of featured ads
$current = 'SELECT * FROM ads  WHERE featured = 1 ORDER BY id ASC LIMIT 1 OFFSET ' . ($beat % $total) . ';'; // current featured ad

基本上这个循环通过所有特色广告给每个特色广告一个节拍(86.4秒)窗口,在那里他们将被给予特别的亮点,例如:

$beat       $total          $current

0           3           0
1           3           1
2           3           2
3           3           0
4           3           1
5           3           2
6           3           0
7           3           1

这很好用,但是我想知道是否有可能消除对$ total查询的需要并使用一个查询来完成相同的操作。

我不会在没有使用子查询的情况下看到这样做但仍然,我想听听你对此的看法。

3 个答案:

答案 0 :(得分:2)

$current = 'SELECT *, FOUND_ROWS(id) as num FROM ads WHERE featured = 1 ORDER BY id ASC LIMIT 1 OFFSET MOD(' . $beat . ', num)';

答案 1 :(得分:1)

不,这是不可能的。 mysql在LIMIT子句中需要显式常量值。你不能把计算放在LIMIT条款中。

答案 2 :(得分:-1)

您无法优化查询。但你可以优化算法。可能你确实需要这样做,但是......))

如果$total >= 1000你永远不会展示一些广告。在任何情况下,某些广告的展示次数都会超过其他广告。

long timestamp = ... // standard timestamp in millis
long period = 86400; // millis
long total = ... // you total query
long offset = (timestamp / period) % total;
current = ... // you last query, but with my offset