SQL;或语法不起作用

时间:2016-01-11 18:10:23

标签: php mysql

好吧所以我有一个sql命令。请参阅下文。

$sql = "SELECT * FROM orders 
        WHERE loggedtime BETWEEN :time AND :times 
        AND name LIKE :keyword OR odryname LIKE :keyword OR pdryname LIKE :keyword 
        OR jlc LIKE :keyword OR odrphone LIKE :keyword 
        OR biid LIKE :keyword OR dstreet LIKE :keyword ";
$q=$con->prepare($sql);
$q->bindvalue(":keyword", "%".$keyword."%");

所以命令一直工作到它的第一个OR ...它将检查记录的时间是否是我放入的,NAME就像是关键字..

命令的唯一部分应该是常量WHERE loggedtime = :time,其余部分应基于关键字是否匹配...但如果该订单上的时间不正确,则根本不应显示任何结果。

3 个答案:

答案 0 :(得分:1)

将其放入()loggedtime BETWEEN :time AND :times,因此您的查询应为:

$sql = "SELECT * FROM orders 
WHERE (loggedtime BETWEEN :time AND :times) 
AND name LIKE :keyword OR odryname LIKE :keyword OR pdryname LIKE :keyword 
OR jlc LIKE :keyword OR odrphone LIKE :keyword 
OR biid LIKE :keyword OR dstreet LIKE :keyword ";

答案 1 :(得分:1)

如您所指定的,有两个主要条件被视为logged time以及与keyword进行比较的其他字段。
您需要使用大括号对逻辑相关的运算符进行分组。
当组合这些条件( AND 条件和 OR 条件)时,使用圆括号非常重要,这样数据库就知道评估每个条件的顺序。
试试这个查询:

$sql = "SELECT * FROM orders 
        WHERE loggedtime BETWEEN :time AND :times 
        AND (name LIKE :keyword OR odryname LIKE :keyword OR pdryname LIKE :keyword 
        OR jlc LIKE :keyword OR odrphone LIKE :keyword 
        OR biid LIKE :keyword OR dstreet LIKE :keyword) ";

答案 2 :(得分:1)

逻辑AND运算符的优先级高于逻辑OR。这在the MySQL documentation中详细记录。

因此,如果没有明确的括号,您当前的语句实际上如下:

SELECT * FROM orders 
    WHERE (loggedtime BETWEEN :time AND :times 
    AND name LIKE :keyword) OR odryname LIKE :keyword OR pdryname LIKE :keyword 
    OR jlc LIKE :keyword OR odrphone LIKE :keyword 
    OR biid LIKE :keyword OR dstreet LIKE :keyword

由于OR的优先级低于AND,因此您需要大括号将所有OR条件组合在一起:

SELECT * FROM orders 
    WHERE loggedtime BETWEEN :time AND :times 
    AND (name LIKE :keyword OR odryname LIKE :keyword OR pdryname LIKE :keyword 
    OR jlc LIKE :keyword OR odrphone LIKE :keyword 
    OR biid LIKE :keyword OR dstreet LIKE :keyword)