【发布时间】:2015-06-04 19:24:15
【问题描述】:
问题是如何动态构建一条语句以从数组$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 来完成,因此我在上面写了问题。
【问题讨论】:
-
你可以使用 mysqli 或 pdo 来做一个准备好的语句并从你的表数组中传递变量。
-
嗨@trixtur,希望从我在数组中列出的选项列表中返回特定的 TABLE_NAME。寻找关于 syntax 的指导 - 如何编写语句。