【发布时间】:2012-08-27 05:33:00
【问题描述】:
考虑两种查询数据库的方式:
使用框架(Yii):
$user = Yii::app()->db->createCommand()
->select('id, username, profile')
->from('tbl_user u')
->join('tbl_profile p', 'u.id=p.user_id')
->where('id=:id', array(':id'=>$id))
->queryRow();
使用字符串连接(分隔 SQL 语句的各个部分):
$columns = "id,username,profile"; // or =implode(",",$column_array);
//you can always use string functions to wrap quotes around each columns/tables
$join = "INNER JOIN tbl_profile p ON u.id=p.user_id";
$restraint = "WHERE id=$id ";//$id cleaned with intval()
$query="SELECT $columns FROM tbl_user u {$restraint}{$join}";
//use PDO to execute query... and loop through records...
用于分页的字符串连接示例:
$records_per_page=20;
$offset = 0;
if (isset($_GET['p'])) $offset = intval($_GET['p'])*$records_per_page;
Squery="SELECT * FROM table LIMIT $offset,$records_per_page";
哪种方法的性能更好?
- PHP 的 PDO 允许将代码移植到不同的数据库中
- 第二个方法可以包装在一个函数中,因此不会重复任何代码。
- 字符串连接允许以编程方式(通过操作字符串)构建复杂的 SQL 语句
【问题讨论】:
-
即使在 Yii 示例中,仍然会有代码在后台连接完全相同的字符串并使用 PDO 或其他适配器将其发送到数据库。所以性能问题是一种自我回答。
标签: php sql performance frameworks