当有LIMIT 5时,JOIN与多个查询

时间:2016-12-05 11:25:18

标签: php mysql preferences

我有两张如下表:

// posts
+----+---------+------------------+-----------+
| id |  title  |      content     | author_id |
+----+---------+------------------+-----------+
| 1  | title1  | content1         | 123       |
| 2  | title2  | content2         | 456       |
| .  | .       | .                | .         |
| .  | .       | .                | .         |
| .  | .       | .                | .         |
+----+---------+------------------+-----------+

// users
+----+-------+
| id |  name |
+----+-------+
| 1  | Jack  |
| 2  | Peter |
| .  | .     |
| .  | .     |
| .  | .     |
+----+-------+

我想选择以下5个帖子:

SELECT * FROM posts WHERE 1 ORDER BY id LIMIT 5

我还需要为每个帖子获取 author 的名称。所以我可以使用这样的JOIN来做到这一点:

SELECT p.*, u.name
FROM posts p
JOIN users ON p.author_id = u.id
WHERE 1
ORDER BY id
LIMIT 5

我可以这样做:

SELECT * FROM posts WHERE 1 ORDER BY id LIMIT 5
// storing results in a PHP array named $results
foreach( $results as $result ) {
    SELECT name FROM users WHERE id =  $result['author_id']
    // storing results in a PHP array named $names
}
// combining $names and $results to make expecting result

那么,哪种方法对于庞大的数据集更有效?换句话说,JOIN之前会LIMIT发生吗?如果是,那么我想通过PHP做这件事会更快,我错了吗?

1 个答案:

答案 0 :(得分:0)

MySQL引擎: InnoDB 使用表中的行级锁定,然后 LIMIT 将与 JOIN 同时工作,获取行直到它找到了5行。