2017-02-19 39 views
1

所以我有搜索虽然6K成员和3K网站这种使用是很好的一个相当大的查询网站上启动,但现在该网站是越来越庞大,其做此查询已开始落后于只是看看网页关于我如何能加快步伐PHP的查询滞后服务器

$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(); 

建议用户有在我的网站和项目,他们赚取金币,然后有项目被看作所以“硬币”什么IM上面做的是抓住一个用户那里硬币更大于1倍,谁拥有项目

+3

是u.username ,w.owner和u.coin ■所有索引 – nogad

+1

http://jan.kneschke.de/projects/mysql/order-by-rand/ –

+1

^笑甚至没有看到的是,为了通过兰特表现死亡http://stackoverflow.com/questions/ 1823306/MySQL的替代品,按订单按兰特 – nogad

回答

0

在大多数评论指出,在查询中使用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); 
0

你需要用两个查询,而不是一做。

获取的符合条件的记录数

$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();