如果我想获得具有特定品牌的product_ids列表。我会这样做:
$id_list = array();
$qry = 'SELECT product_id FROM products WHERE product_brand = :brand';
$STH = $this->pdo->prepare($qry);
$STH->execute(array("brand" => $brand));
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch())
{
$id_list[] = $row['product_id'];
}
有更快更有效的方式吗?看起来如果我只选择1列,应该有更好的方法来选择/插入数组。
答案 0 :(得分:4)
$STH->setFetchMode(PDO::FETCH_COLUMN,0);
$id_list = $STH->fetchAll();
真的更快吗?当地的BenchmarK:
$ cat 1.php
<?php
$d = new PDO('mysql:localhost');
$qry = 'SELECT SQL_NO_CACHE bar FROM test.foo'; //for completeness sake: foo has 400 rows
$stmt = $d->query($qry);
$stmt->setFetchMode(PDO::FETCH_COLUMN,0);
$check = $stmt->fetchAll();
?>
$ cat 2.php
<?php
$d = new PDO('mysql:localhost');
$qry = 'SELECT SQL_NO_CACHE bar FROM test.foo'; //for completeness sake: foo has 400 rows
$stmt = $d->query($qry);
$check = array();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()){
$check[] = $row['bar'];
}
?>
$ time (for i in {1..100}; do php 1.php; done;)
real 0m4.507s
user 0m2.392s
sys 0m1.288s
$ time (for i in {1..100}; do php 2.php; done;)
real 0m6.830s
user 0m3.352s
sys 0m2.328s
..所以,至少我的服务器上的这个脚本差异更快......