Question is how to dynamically build one statement to return just one table name from array $tables
that has the most records that match criteria $table.status = 'ready'
.
I already understand I could create a combined subquery and count each, then sort using small php function, but part of my mission is to use MySQL statement for the heavy lifting because I am assuming it will be faster.
For example,
$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 .= "????" ;
And as stated in the question, I want to select based on the highest count(*)
of rows where $table.status = 'ready'
(My server environment is PHP 5.3.29 and MySql 5.1.73-cll. )
I can already solve this with one query and some php but I am asking if there is an answer to just return the TABLE_NAME with the one statement.
For example, I can solve like this:
$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
Again, it solves the question with one query but forces me into php to complete, thus the question I wrote above.
If you look here you can see how to pass in variables and how to do a prepared statement:
http://php.net/manual/en/pdo.prepared-statements.php
It is important to use prepared statements to avoid SQL injection.
$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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.