1

This might be a duplicated question of mysql union vs multiple queries except the question is too general, and this question for specified case.

First of all, there are two options that I am thinking which one is better in term of performance wise. First one is getting previous and next row with separated query. The following is a pseudo code:

sql->query("SELECT * FROM tbldata WHERE id < 3 ORDER BY id DESC LIMIT 1");
$prev = sql->getRecord();
sql->query("SELECT * FROM tbldata WHERE id > 3 ORDER BY id LIMIT 1");
$next = sql->getRecord();

Another solution is to use only one query with UNION.

sql->query("(SELECT * FROM tbldata WHERE id > 3 ORDER BY id DESC LIMIT 1) UNION
            (SELECT * FROM tbldata WHERE id < 3 ORDER BY id LIMIT 1)");
$row = sql->getRecords();
if (count($row) > 1) {
   $prev = $row[0];
   $next = $row[1];
} elseif (count($row) == 0) {
} elseif ($row[0]->id > 3) {
   $next = $row[0];
} else {
   $prev = $row[0];
}

Which one is a best practice for this type of problem?

4

3 回答 3

1

如果我不得不猜测,UNION 总体上可能更快,只是因为它减少了对数据库的请求数量,但我强调,这是一个猜测,它取决于许多因素,唯一知道的方法是分析代码和检查。

实际上,它可能几乎没有什么区别。除非有不寻常的情况,比如与数据库服务器的连接速度非常慢。

我的建议是,使用使代码更整洁和更易于阅读的任何一种,直到有理由更改它 - 即。直到您的系统分析表明这是系统中的瓶颈。

于 2013-09-05T06:00:38.747 回答
1

根据我的经验,我认为UNION比其他人更快。

也试试这个。

SELECT * , IF( id >3, 1, 0 ) AS NextFlag, IF( id <3, 1, 0 ) AS PrevFlag FROM tbldata
WHERE id <= 3+1
HAVING NextFlag =1
OR PrevFlag =1
ORDER BY id DESC
LIMIT 2 
于 2013-09-05T07:04:24.270 回答
-1
$sql->query('SELECT t.*
             FROM table t
             WHERE t.id IN ('.($id-1).', '.($id+1).')');
$rows = sql->getRecords();

$next = $prev = false;

if (is_array($rows) && $rows) {
    $next = $rows[0];

    if (isset($rows[1])) {
        $prev = $rows[1];         
    } elseif ($rows[0]->id < $id) {
        $prev = $next;
        $next = false;
    }
}

一个带有 PRIMARY 索引的请求(如果 id 是您的 PRIMARY KEY)。比 UNION 或 2 个请求更好。

于 2013-09-05T06:06:54.967 回答