我需要根据用户输入(复选框)过滤MySQL数据,但我使用它的查询没有按预期工作。
我使用3列(和3组复选框)来过滤数据:类型,状态和bhk(所有整数)。
if ($filter_type != NULL) {
foreach ($filter_type as $type=>$value) {
if ($type === 0) {
$type_cond = "AND t2.type = " . $value;
} else {
$type_cond .= " OR t2.type = " . $value;
}
}
}
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN property t2 ON t2.id = t1.id
WHERE t2.use = ?
' . $type_cond . '
' . $status_cond . '
' . $bhk_cond . '
' . $filter_city . '
' . $filter_zone . '
LIMIT ?, ?'))
其他两个相同。在表property
中,我有1行:type = 2,status = 0和bhk = 3.
我选中复选框类型1和2,bhk 1(AND type = 1 OR type = 2 AND bhk = 1
):没有返回,好的。如果我继续检查bhk 3:它返回行,好的。但是如果我还想按状态过滤:
AND t2.type = 1 OR t2.type = 2
AND t2.bhk = 1 or t2.bhk = 3
AND t2.status = 1 OR t2.status = 2
为什么上面的句子返回行?最后一个AND和OR不是真的。我需要的是:只返回与3个AND / OR匹配的数据(如果不使用3个组中的一个,则返回2个。)
我该怎么做?
我也有些疑惑:(第一个例子)
AND t2.type = 1 OR t2.type = 2
AND t2.status = 0 --OR t2.status = 1
AND t2.bhk = 1
不返回行...但如果我添加OR t2.status = 1
,它将返回行...为什么?
(第二个例子)
AND t2.type = 1 OR t2.type = 2
AND t2.status = 1
AND t2.bhk = 3 --OR t2.bhk = 1
没有任何意义......请赐教。
第二个问题是:AND does t2.status = 0
为什么不返回行,AND t2.status = 0 OR t2.status = 1
呢? (基于第一个例子)
编辑:添加新脚本(使用IN()
代替OR
)
$type_count = count($filter_type);
$type_cond = '';
if ($filter_type != NULL) {
foreach ($filter_type as $type=>$value) {
if ($type === 0) {
$type_cond = 'AND t2.type IN ( ' . $value;
if ($type_count === 1) {
$condition .= ')';
}
} else if ($type < $count) {
$type_cond .= ', ' . $value;
} else {
$type_cond .= ', ' . $value . ')';
}
}
}
答案 0 :(得分:1)
您的过滤器:
AND t2.type = 1 OR t2.type = 2
AND t2.bhk = 1 or t2.bhk = 3
AND t2.status = 1 OR t2.status = 2
还可以写成L
AND t2.type = 1 OR (t2.type = 2
AND t2.bhk = 1) or (t2.bhk = 3
AND t2.status = 1) OR t2.status = 2
即使t2.status = 2
无论其余部分如何,它都会返回TRUE。你可以使用适当的parantheses来修复它,但如果你使用IN
AND t2.type IN (1,2)
AND t2.bhk IN (1,3)
AND t2.status IN (1,2)