mysql查询where子句使用AND和OR

时间:2015-02-19 22:33:54

标签: mysql sql

有人可以帮我解决这个问题:

 SELECT SQL_CALC_FOUND_ROWS * 
          FROM Punches
          WHERE Serial LIKE '%123%'
          OR Badge LIKE '%123%'
          OR Search_Date LIKE '%123%'
          OR Punch_Time LIKE '%123%'
          OR Device_Name LIKE '%%'
          AND Company_ID = '0002'
          LIMIT 0, 20

基本上我想搜索所有这些像LIKE 123但必须有Company_ID =' 0002'的字段。此查询返回没有Company_ID =' 0002'

的行

2 个答案:

答案 0 :(得分:2)

试试这个......

 SELECT 
    SQL_CALC_FOUND_ROWS * 
 FROM 
    Punches
 WHERE 
    (Company_ID = '0002') AND 
    (Serial LIKE '%123%'
     OR Badge LIKE '%123%'
     OR Search_Date LIKE '%123%'
     OR Punch_Time LIKE '%123%'
     OR Device_Name LIKE '%%')
 LIMIT 0, 20

答案 1 :(得分:1)

1)AND的优先级高于OR。只需添加括号:

SELECT SQL_CALC_FOUND_ROWS * 
          FROM Punches
          WHERE (... OR ... OR ...)
          AND Company_ID = '0002'
          LIMIT 0, 20

2)Device_Name LIKE '%%'永远是真的。