我得到了像这样的mysql表
id | type | number
1 | c | 2
2 | c | 10
3 | c | 20
我还得到了带有值的PHP数组:
$array[c] = 5;
$array[d] = 10;
我想做这样的事情
( SELECT * FROM table WHERE number >= $array[ type ] )
这样类型可以某种方式从mysql列获取并用于从数组中找到正确的值。
这有点棘手,但我不确定我能提出多好的要求。
答案 0 :(得分:1)
这不是最优雅的方式,但是这样吗?
$where = "WHERE ";
foreach($array as $key => $value)
{
$where .= "(type = $key AND number >= $value) OR";
}
$where = substr($where, 0, strlen($where)-2);
您必须将其附加到您的select语句,然后显然运行查询。
希望能让其他人接受并提供更优雅的解决方案。
答案 1 :(得分:0)
试试这个:
$type = 'c';
$query = "SELECT * FROM table WHERE number >= " . intval( $array[ $type ] ) . " AND type = '" . $type . "'";
答案 2 :(得分:0)
尝试分两步完成: 在使用sql查询之前,在数组中放入类型为
的值然后在一段时间
( SELECT * FROM table WHERE number >= $array[$i] )
其中$ i是while循环的索引
答案 3 :(得分:0)
可能比使用大量WHERE子句好一点就是这样: -
SELECT *
FROM table a
INNER JOIN
(SELECT 'c' AS RowType, 5 AS RowVal
UNION
SELECT 'd', 10) Sub1
ON a.type = Sub1.type AND a.number >= Sub1.RowVal
设置一个只获取常量的子选择,然后在该子选择和现有表之间进行连接。
在php中做了类似这样的事情: -
<?php
$SubQuery = array();
foreach ($array AS $key=>$value)
{
$SubQuery[] = "SELECT '$key' AS RowType, $value AS RowVal";
}
$sql = "SELECT *
FROM table a
INNER JOIN (".implode(" UNION ", $SubQuery).") Sub1
ON a.type = Sub1.type AND a.number >= Sub1.RowVal";
?>