我的商店中的产品有国家/地区限制,并且查询速度很慢,无法从产品表中选择值为 1
的所有国家/地区列。
我在我的商店中选择了所有活跃的国家:
$ids = select id from country where active = 1;
然后我选择在产品中活跃的所有国家/地区:
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/