将多个WHERE .. AND语句添加到同一SQL查询中

时间:2014-09-14 18:48:22

标签: mysql sql

我需要编写一个结合了可变数量的AND WHERE语句的查询。

一个陈述看起来像

SELECT name
FROM users
WHERE field_id=16
AND value BETWEEN 1 AND 100

但我需要从可变数量的字段返回一个结果数组,因此field_id为16,18,20,25,每个field_id都有一个特定的" AND值...&#34 ;标准。

我怎么能这样做才能返回一组值?

我也从html表单中获取搜索条件并使用php(wordpress)处理它

2 个答案:

答案 0 :(得分:1)

如果field_id需要与value字段条件相关,那么您需要AND field_idvalueOR SELECT name FROM users WHERE (field_id=16 AND value BETWEEN 1 AND 100) OR (field_id=17 AND value between 101 and 199) OR (field_id=18 AND value between 201 and 299) OR (... 每套标准。

IN

您可能也在寻找SELECT name FROM users WHERE (field_id IN (16,17,18) AND value IN (100,200,300)) ... 声明。看起来像这样。

{{1}}

Fiddle

答案 1 :(得分:0)

您可以使用AND和OR条件的组合:

SELECT name
FROM users
WHERE (field_id=16 AND value BETWEEN 1 AND 100) 
  OR (field_id=18 AND value BETWEEN 1 AND 150)
  OR (field_id=20 AND value BETWEEN 10 AND 50)
  OR (field_id=25 AND value BETWEEN 100 AND 500)
....