我正在尝试获取表中应满足以下条件的项目数
status = active
type = Pre-order
date = $date_input
OR
status = active
type = Both
date = $date_input
我试着用这个说法,但我确信它是一团糟。
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')
我也尝试过,但没有效果
SELECT COUNT(id) as count_date from date_restriction
where date='$date_input' AND status='active' AND type='Pre-order' OR type='Both'
当您混合了或子句所需的AND和OR条件时((
SELECT COUNT(id) as count_date
from date_restriction
where date='$date_input'
AND status='active'
AND ( type='Pre-order' OR type='Both')
或代替几个或条件,您可以使用IN子句
AND type IN ('Pre-order', 'Both')
无论如何,您应该避免在SQL中使用php-var,否则将面临sqlinjection的风险。。为了避免这种情况,您应该查看为数据库驱动程序准备的语句和绑定参数
您的代码应该可以工作。我会这样写:
select count(*) as count_date
from date_restriction
where date = ? AND status = 'active' AND
type in ('Pre-order', 'Both');
注意:?
用于参数,因此您不会将查询字符串与输入值混淆。
如果我必须猜测为什么这不起作用,我会推测其中一个或两个日期都有时间成分。你可以试试:
where date(date) = date(?) . . .
以确保您在日期上匹配,而不考虑时间。
选择count(id(作为count_dateFROM日期_限制WHERE date='$date_input'AND state='active'AND(type='Pre-order'或type='Both'(;在这里,日期和状态这两个字段在您的案例中是常见的;因此,不要将其包装在括号中,而只为类型字段添加OR条件,并在WHERE子句中用and将其替换。