我有一个棘手的问题,我想看看是否有更简单的解决方法。
我已经说过了
$numbers= $_GET['numbers']; //resulting in $numbers=array(1,2,3)
我的理想结果会搜索$ numbers(1,2,3):
SELECT * FROM database WHERE numbers LIKE('%1%' OR '%2%' OR '%2%')
答案 0 :(得分:2)
$like_part = implode(' OR ', array_map(function($i) {
return "(_utf8 '%{$i}%' USING latin1)";
}, $numbers)
);
答案 1 :(得分:1)
效果:
$ query =“select * from table
where condition like('text before'”.implode(“'text after text before'”,$ array)。“'text after')”
$ query =“select * from table
其中数字如(\”_ utf8'%“。implode(”%'使用latin1 \“,$ _GET ['numbers'])。”%'使用latin1或_utf8'%\“)
[不确定内爆是针/干草堆还是反之亦然]
答案 2 :(得分:1)
使用foreach构建where字符串,然后将其添加到查询中。
$query = '...';
$where = '';
foreach ($numbers as $number) {
$where .= ...
}
$query .= $where;
我不会提到你应该normalize your tables并使用准备好的查询。
答案 3 :(得分:1)
无需为Array的每个元素注入许多OR
个运算符。相反,您可以使用rlike (the regex matcher operator of MySQL)并在很大程度上简化代码:
$numbers = array(1,2,3);
$sql = 'SELECT * from `database` WHERE number rlike "^'.implode('|', $numbers).'$"';
// $sql becomes: SELECT * from `database` WHERE number rlike "^1|2|3$"
答案 4 :(得分:1)
此代码:
<?php
$numbers = array(1,2,3);
$sql = "SELECT * FROM table WHERE numbers LIKE ('%" . implode("%' OR '%", $numbers) . "%')";
产生此查询:
SELECT * FROM table WHERE numbers LIKE ('%1%' OR '%2%' OR '%3%')
答案 5 :(得分:0)
1 - SELECT * FROM b AS B INNER JOIN a AS A ON A.a=B.a WHERE A.a RLIKE '^1-|^2-|^3'
2 - SELECT * FROM b AS B INNER JOIN a AS A ON A.a=B.a WHERE (A.a LIKE '1-%' OR A.a LIKE '2-%' OR A.a LIKE '3-%')
第一次查询大约
第二次查询大约
Foreach 接管了
配置
(i.e. 1,2,3... in RLIKE '^1-|^2-|^3....etc')
memory_get_usage();
计算的内存使用率欢迎提出异议。