php - MySQL语法从多个符合条件的选项中选择表名

标签 php mysql

问题是如何动态构建一条语句,以仅从数组 $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/

相关文章:

php - 如果存在符合条件的相应行,则选择行?

php - 在mysql中如何使用增量i=1,i++?

mysql join 从2行获取信息

java - 使用 where 子句仅计算大 MySQL 表上的最后 100k 条记录

php - 无法更改 WordPress tinymce 编辑器字体

javascript - 如何在未完成的情况下从 ajax 触发的 PHP 调用获取更新?

php - 它是查看还是加入我需要的这个 mysql 练习

php - 了解 ajax 画廊和类别

php - 查询返回先前函数的内容

php - MYSQL 从表中选择,获取表中最新/最后 10 行