问题是如何动态构建一条语句,以仅从数组 $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 .= "????" ;
正如问题中所述,我想根据 $table.status = 'ready'
行的最高 count(*)
进行选择
(我的服务器环境是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 来完成,因此我在上面写了这个问题。
最佳答案
如果您看这里,您可以了解如何传递变量以及如何执行准备好的语句:
http://php.net/manual/en/pdo.prepared-statements.php
使用准备好的语句来避免 SQL 注入(inject)很重要。
$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.
关于php - MySQL语法从多个符合条件的选项中选择表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30652401/