MySQL根据以前的查询选择行

时间:2015-06-07 22:55:09

标签: php mysql

$clicks = mysqli_real_escape_string($conn,$_POST['clicks']);
$modifier = 10*$clicks;

$result = mysqli_query($conn,"SELECT * FROM posts ORDER BY freshness LIMIT $modifier,10");

while($row = mysqli_fetch_assoc($result)){
    $posts[] = $row;
}

$result2 = mysqli_query($conn,"SELECT * FROM comments ORDER BY time WHERE ????");

while($row2 = mysqli_fetch_assoc($result2)){
    $comments[] = $row2;
}

对于$result2,如何从WHERE中选择10个帖子ID(即$row['id'])中的每一个$result?否则,我会不必要地选择表格中的每一条评论。

2 个答案:

答案 0 :(得分:3)

为什么不在一个查询中完成所有操作?

 $modifier = 10*$clicks;

 $query = "SELECT *
    FROM posts 
    INNER JOIN comments
    ON posts.id = comments.post_id
    ORDER BY posts.freshness 
    LIMIT '$modifier'";

答案 1 :(得分:1)

您可以使用当前代码和MySQL的IN子句执行以下操作。

while($row = mysqli_fetch_assoc($result)){
    // Here we use the ID for the array key.
    $posts[$row['id']] = $row;
}

// Here we get the array keys and implode the IDs into a comma-separated list.

$row_ids = implode(',', array_keys($posts));

// And here we plug it into an `IN` statement.

$result2 = mysqli_query($conn,"SELECT * FROM comments WHERE post_id IN ({$row_ids}) ORDER BY `time`");

// May want to change the 'time' above into a non-reserved word...

while($row2 = mysqli_fetch_assoc($result2)){
    // Here we add the comments into arrays associated by post_id.
    $comments[$row2['post_id']][] = $row2;
}

是的,我意识到制作一个JOIN看起来很性感。它也可能产生很多开销。现在对场景进行基准测试......为此,我为帖子(1000个帖子)和评论(带有随机帖子ID的5000个评论)创建了样本表,用于基准测试。 (时间戳索引。)

案例1:首先选择按日期排序的50个帖子。然后使用带有上述帖子ID的IN选择所有评论,再按日期排序。 (使用此测试数据在每个循环中返回50个帖子和268条评论。)结果:在3.0888秒内进行1000次循环(平均0.0030888秒)。

案例2 :使用@OllyTeneriffe的JOIN示例。 (我将LIMIT设置为268以匹配案例1的数据量,在评论中注明的限制条款问题上“作弊”。)在单个循环中获取结果。结果:在25.7868秒内进行1000次循环(平均0.0257868秒)。

使用LIMIT 200重复测试(产生200个帖子+ 971条评论)。 案例1: 8.2992秒(平均0.0082992秒)。 案例2: 33.5089秒(平均0.0335089)。结果并不像连接看起来那么性感。在这种情况下,“简单”方法的速度要快一个数量级。

相关问题