MySQL:获取以“ ctr_”和值1开头的表的所有列

时间:2018-07-11 11:20:34

标签: 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的列?

1 个答案:

答案 0 :(得分:0)

尝试以下

// 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
    // ....
  }
}