【问题标题】:Php query lagging serverphp查询滞后服务器
【发布时间】:2017-02-19 01:12:48
【问题描述】:

所以我有一个相当大的查询,虽然搜索了 6k 个成员和 3k 个网站,这在网站启动时使用得很好,但现在网站变得越来越大,这个查询的页面已经开始滞后,只是在寻找有关如何操作的建议我可以加快速度

$stmt212 = $db->prepare('SELECT * 
FROM websites w
    LEFT JOIN users u ON u.username = w.owner
WHERE u.coins >= ? 
ORDER BY RAND() 
LIMIT 1');
$stmt212->execute( array('1') ) ;
$row212 = $stmt212->fetch();

用户在我的网站上有“硬币”和他们赚取硬币的物品,然后那里的物品会被查看,所以我上面所做的就是抓住硬币大于 1 并且有物品的用户

【问题讨论】:

标签: php


【解决方案1】:

您需要处理两个查询而不是一个。

获取符合条件的记录数

$stmt212count = $db->prepare("
    SELECT
        count(*)
    FROM
        websites w
    INNER JOIN
        users u ON
            u.username = w.owner
            AND u.coins >= :coins
");
$stmt212count->bindValue('coins', 1, PDO::PARAM_INT);
$stmt212count->execute();
$row212count = $stmt212count->fetch(PDO::FETCH_COLUMN);

随机选择一行

# random row offset
$offset = rand(0, $row212count-1); 

如果您已打开 PDO 模拟准备,请使用此语句

$stmt212 = $db->prepare(sprintf(
    "
        SELECT
            *
        FROM
            websites w
        INNER JOIN
            users u ON
                u.username = w.owner
                AND u.coins >= :coins
        LIMIT %d,1
    ",
    $offset
);
$stmt212count->bindValue('offset', $offset, PDO::PARAM_INT);

如果您不使用 PDO 模拟准备,请使用它

$stmt212 = $db->prepare("
    SELECT
        *
    FROM
        websites w
    INNER JOIN
        users u ON
            u.username = w.owner
            AND u.coins >= :coins
    LIMIT :offset,1
");

这两个语句都用这个

$stmt212count->bindValue('coins', 1, PDO::PARAM_INT);
$stmt212count->execute();
$row212 = $stmt212->fetch();

【讨论】:

    【解决方案2】:

    正如大多数 cmets 所述,在查询中使用RAND()可能是一件坏事。我假设两列都没有索引,这使得数据库驱动程序非常困难。

    为了保持你的数据库结构和性能,你可以让 PHP 为你随机化你的索引:

    $stmt = $db->prepare('
      SELECT * 
      FROM websites w
      LEFT JOIN users u ON u.username = w.owner
      WHERE u.coins >= ?
    ');
    
    $stmt->execute(array('1')); // why are you not checking if this succeeds?
    $result = $stmt->fetchAll(PDO::FETCH_NUM);
    $result = array_rand($result);
    
    print_r($result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多