php - MySQL:获取表的所有以名称 "ctr_"和值 1 开头的列

标签 php mysql

我的商店中的产品有国家/地区限制,并且查询速度很慢,无法从产品表中选择值为 1 的所有国家/地区列。

  1. 我在我的商店中选择了所有活跃的国家:

    $ids = select id from country where active = 1;
    
  2. 然后我选择在产品中活跃的所有国家/地区:

    foreach $ids as $id { select ctr_{$id} from product where ctr_{$id} = 1;
    

是否有更快的方法来获取以 ctr_* 开头且值等于 1 的列?

最佳答案

尝试以下操作

// first get the columns
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='product' AND COLUMN_NAME LIKE 'ctr_%'";
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn),E_USER_ERROR);
$cols = Array();
while($row = mysqli_fetch_row($result)) $cols[] = $row[0];

// then build the query
if(count($cols))
{
  $query = 'SELECT '.implode(',', $cols).' FROM product WHERE 1 IN ('.implode(',',$cols).')';
  $result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn), E_USER_ERROR);
  while($row = mysqli_fetch_assoc($conn,$result))
  {
    // do something with the row
    // ....
  }
}

关于php - MySQL:获取表的所有以名称 "ctr_"和值 1 开头的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51284183/

相关文章:

MySQL: "NOT IN()"函数是否不允许结果集中出现 'NULL'值?

php - 使用 PHP 循环遍历数据库并填充 HTML 表

php - 准备好的语句返回 0 而不是 1,为什么?

php - 数据库、字符编码、PDF 和 XML

PHP - mysqli_query 不工作

每个应用程序的 php 设置

mysql - 无法使用 MySQL 在 Windows 上运行 Rails 服务器

phpexcel - 如何更改 excel 整列的数据类型

php - 为什么记录没有出现在数据库中

php - magento 根目录中的 "Mage"文件