SQL WHERE,OR和AND

时间:2016-05-17 08:13:43

标签: sql

我尝试SELECT来自此数据库WHERE statement_fromusername = = $username但是这不是{\ n}}工作正常。我已经查看了之前提出的类似问题,但不确定如何在此查询中实现先前的答案。

   "SELECT * FROM `usr_statements` WHERE `statement_from` = '$username' 
    OR `username` = '$username' AND `statement_timestamp` > '$start_date'
    AND `statement_timestamp` < '$end_date' ORDER BY `statement_ref` DESC"

我想要实现的是选择数据库中statement_fromusername = = $username的所有结果。

2 个答案:

答案 0 :(得分:8)

目前您的查询已经过验证,如此

WHERE `statement_from` = '$username' 
    OR (`username` = '$username' AND `statement_timestamp` > '$start_date')
    AND `statement_timestamp` < '$end_date'

因为AND高于<{em> 优先级高于OR所以AND将首先评估。

您需要添加正确的括号

SELECT * FROM `usr_statements` 
WHERE (`statement_from` = '$username' 
    OR `username` = '$username') 
   AND `statement_timestamp` > '$start_date'
   AND `statement_timestamp` < '$end_date' 
ORDER BY `statement_ref` DESC

此外,您可以使用IN运算符执行 Jarlh 在评论中提到的

SELECT * FROM `usr_statements` 
WHERE $username in (statement_from, username)
   AND `statement_timestamp` > '$start_date'
   AND `statement_timestamp` < '$end_date' 
ORDER BY `statement_ref` DESC

答案 1 :(得分:0)

运营商的优先级为NOT - &gt; AND - &gt; OR,所以你需要一些药物治疗:

"SELECT * FROM `usr_statements` WHERE (`statement_from` = '$username' 
    OR `username` = '$username') AND `statement_timestamp` > '$start_date'
    AND `statement_timestamp` < '$end_date' ORDER BY `statement_ref` DESC"