首页 > 解决方案 > 在 where 子句中使用两组条件

问题描述

我正在尝试获取表中应该满足这些条件的项目数

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'

标签: mysqlsql

解决方案


如果您混合了 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')

或几个或条件你可以使用 IN 子句

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

无论如何,你应该避免在 SQL 中使用 php var 你有 sqlinjection 的风险 .. 为了避免这种情况,你应该看看你的数据库驱动程序的准备好的语句和绑定参数


推荐阅读