问题是如何动态构建一个语句,以便从数组$tables
中返回一个表名最多且记录符合$table.status = 'ready'
的记录。
我已经明白我可以创建一个组合子查询并计算每个,然后使用小的PHP函数排序,但我的任务的一部分是使用MySQL语句进行繁重的工作,因为我假设它将更快。
例如,
$tables = array('foo','bar','beyond','repair') ;
// start building the statement
$query = "SELECT TABLE_NAME" ;
// ? What else add here $query .= '????' ;
// loop to build part of the statement
foreach($tables as $table){
// create this statement dynamically
// somehow I need to incorporate count(*)
// and $table.status = 'ready'
// note: all tables in $tables have a column named 'status'
// ? What else add here $query .= "????" ;
}
// add any remaining syntax
// ? What else add here $query .= "????" ;
正如问题中所述,我想根据count(*)
$table.status = 'ready'
进行选择
(我的服务器环境是PHP 5.3.29和MySql 5.1.73-cll。)
我已经可以通过一个查询和一些php来解决这个问题,但我想问一下是否只有一个语句返回TABLE_NAME的答案。
例如,我可以这样解决:
$choices = array() ;
$query = "SELECT";
foreach($tables as $table) {
// loop and create subqueries, append table name with _count and we will strip it later
$query .= "(SELECT COUNT(*) FROM $table WHERE $table.status = 'ready') as ".$table."_count," ;
}
$query = rtrim($query, ',');
$result = mysqli_query($db_connection,$query) or die("Sql error: " . mysqli_error($db_connection));
while($row = mysqli_fetch_assoc($result)) {
while (list($key, $val) = each($row)) {
$choices[ str_replace('_count', '', $key) ] = $val;
}
}
arsort($choices ); // sort by value reverse
$table_with_highest_count = key($choices) ; // the key will be table name now
同样,它用一个查询解决了这个问题,但强迫我完成php,这就是我上面写的问题。
答案 0 :(得分:0)
如果你看这里,你可以看到如何传递变量以及如何做一个准备好的声明:
http://php.net/manual/en/pdo.prepared-statements.php
使用预准备语句来避免SQL注入非常重要。
$tables = array('foo','bar','beyond','repair') ;
$maxcount = 0;
$maxTableName = '';
foreach ($tables as $table) {
$stmt = $dbh->prepare("SELECT count(*) FROM :name WHERE status = 'ready'");
$stmt->bindParam(':name', $table);
$count = $stmt->fetch();
if ($count > $maxCount) {
$maxCount = $count;
$maxTableName = $table;
}
}
// Now $maxTableName is the one you are looking for.