我给出了一段非常丑陋的代码,它结合了PHP循环和SQL查询来检索一些ID,我必须折射器。我的计划是将PHP迭代合并到查询中,但我想知道a.这样做是否会影响结果,b.它确实对性能有很好的影响。
以下是脚本当前状态的手势:
$additional_conditions = [
"test_column1 = 'b1' OR test_column1 = 'b2' ",
"test_column2 = 'c1' OR test_column2 = 'c2' ",
"test_column3 = 'd1' OR test_column3 = 'd2' ",
"test_column4 = 'e1' OR test_column4 = 'e2' ",
"test_column5 = 'f1' OR test_column5 = 'f2' ",
];
$query = 'SELECT * from test_table WHERE test_column = 1 AND %s';
foreach ($additional_conditions as $additional_condition)
{
$result = mysqlQuery(sprintf($query, $additional_condition));
while ($data = mysqli_fetch_assoc($result)) {
// do something with the data
}
}
我正在考虑将其更改为:
$query = <<<QUERY
SELECT * from test_table WHERE test_column = 1 AND (
(test_column1 = 'b1' OR test_column1 = 'b2') OR
(test_column2 = 'c1' OR test_column2 = 'c2') OR
(test_column3 = 'd1' OR test_column3 = 'd2') OR
(test_column4 = 'e1' OR test_column4 = 'e2') OR
(test_column5 = 'f1' OR test_column5 = 'f2')
)
QUERY;
$result = mysqlQuery($query);
while ($data = mysqli_fetch_assoc($result)) {
// do something with the data
}
数据库引擎将优化查询以使其更高效。执行繁重的数据库查询通常比执行大量虚拟查询更好。