duanmen8491 2015-07-23 14:56
浏览 43

使用限制更快地通过SQL表导航

My website has a menu with some items, and there are three pages. Using jQuery AJAX, I make a post request to a PHP script with the page number, page 1, page 2 or page 3.

I then use the following to select the appropriate rows.

$page = intval($_POST["page"]);
$perpage = 56;


$calc = $perpage * $page;
$start = $calc - $perpage;

$sql = "SELECT market_items.id, market_items.market_hash_name, market_items.icon_url_large, market_items.name_color, market_items.inprogress, item_price.market_name, item_price.avg_price_7_days FROM market_items JOIN item_price ON market_items.market_hash_name=item_price.market_name WHERE inprogress='0' AND pending='0' AND avg_price_7_days >= '0.50' ORDER BY avg_price_7_days DESC LIMIT $start, $perpage";
$result = mysqli_query($conn, $sql);

As you can see, a post input of page=1 will display rows 1 to 56, page = 2 57 to 112, and so on.

The thing is, I have to make 3 queries to see 3 pages, one for each. Is there a faster way to do this? The lag to load a page is really quite noticeable (about 1.5 seconds to execute the query). I was thinking if I could execute the query once, and then navigate in the result set using mysqli_fetch_assoc($result)), if this is possible.

  • 写回答

1条回答 默认 最新

  • douyang2530 2015-07-23 15:32
    关注

    Here is your original query,

    SELECT
        market_items.id,
        market_items.market_hash_name,
        market_items.icon_url_large,
        market_items.name_color,
        market_items.inprogress,
        item_price.market_name,
        item_price.avg_price_7_days
    FROM
        market_items
    JOIN
        item_price
        ON
        market_items.market_hash_name=item_price.market_name
    WHERE
        inprogress='0'
    AND
        pending='0'
    AND
        avg_price_7_days >= '0.50'
    ORDER BY
        avg_price_7_days DESC
    LIMIT
        $start, $perpage
    

    First of all, injecting $start and $perpage is insecure, also run it when testing without cacheing, This will only work if you haven't cached it already

    SELECT SQL_NO_CACHE ...
    

    If you have ran the query you must clear the cache first,

    RESET QUERY CACHE;
    

    see also: Clear MySQL query cache without restarting server

    Bench mark the speed, then test it without the order by bit. Make sure your indexing is proper. Make sure you have index on the sort field etc. Then if there is significant issue with sort in the query vs not sort, we may have to do more work.

    You cant optimize the query by having it cached, it will always be fast after the first run.

    评论

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算