简体   繁体   English

在 where 子句中使用两组条件

[英]Using two sets of conditions in where clause

I'm trying to get the count of items in my table where it should satisfy these conditions我正在尝试获取表中应该满足这些条件的项目数

status = active
type = Pre-order
date = $date_input

OR

status = active
type = Both
date = $date_input

I'm trying to use this statement but I'm pretty sure it's messed up.我正在尝试使用此声明,但我很确定它搞砸了。

SELECT COUNT(id) as count_date from date_restriction
where (date='$date_input' AND status='active' AND type='Pre-order') 
OR (date='$date_input' AND status='active' AND type='Both')

I also tried this to no avail我也试过这个无济于事

SELECT COUNT(id) as count_date from date_restriction
where date='$date_input' AND status='active' AND type='Pre-order' OR type='Both'

Whe you have mixed AND and OR condition you need () for the or clause如果您混合了 AND 和 OR 条件,则 or 子句需要 ()

SELECT COUNT(id) as count_date 
from date_restriction
where date='$date_input' 
AND status='active' 
AND ( type='Pre-order' OR type='Both')

or instear of several or condition you could use a IN clause或几个或条件你可以使用 IN 子句

 AND  type IN ('Pre-order', 'Both')

anyway you should avoid the use of php var in SQL you are at risk for sqlinjection.. for avoid this you should take a look at prepared statement and binding param for your db driver无论如何,您应该避免在 SQL 中使用 php var,您有 sqlinjection 的风险。为避免这种情况,您应该查看为您的数据库驱动程序准备好的语句和绑定参数

Your code should work.您的代码应该可以工作。 I would write this as:我会这样写:

select count(*) as count_date
from date_restriction
where date = ? AND status = 'active' AND
      type in ('Pre-order', 'Both');

Note: The ?注意: ? is for a parameter so you are not munging the query string with input values.是用于参数,因此您不会使用输入值修改查询字符串。

If I had to guess why this isn't working, I would speculate that one or both of the dates have a time component.如果我不得不猜测为什么这不起作用,我会推测一个或两个日期都有时间成分。 You might try:你可以试试:

where date(date) = date(?) . . . 

to be sure you are matching on the date, regardless of time.确保您在日期匹配,无论时间如何。

SELECT count(id) as count_date FROM date_restriction WHERE date='$date_input' AND status='active' AND (type='Pre-order' OR type='Both'); SELECT count(id) as count_date FROM date_restriction WHERE date='$date_input' AND status='active' AND (type='Pre-order' OR type='Both'); Here, date and status both fields are common in your case;在这里,日期和状态这两个字段在您的情况下都很常见; hence, don't wrap it in parenthesis whereas, add OR condition for type field only and con-cat it with AND in WHERE clause.因此,不要将其包装在括号中,而仅为类型字段添加 OR 条件,并在 WHERE 子句中将其与 AND 结合起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM