我正在尝试根据多个可能的值过滤多个列中的数据。 如果我使用下面的语句,我会得到匹配的结果但是太多。例如,如果我只传递状态[Lead,Customer],那么我就得到那些记录。如果我添加SalesRep [cary],那么我也会得到所有匹配的Cary记录,其中包括一些其他状态如Prospect。
SELECT id, `ContactID`, Status, SalesRep, LeadSource, `PhysicalAddress_State`, `PhisicalAddress_Zip` FROM Contacts WHERE
Status IN ('Lead','customer') OR
SalesRep IN('cary') OR
LeadSource IN ('') OR
PhysicalAddress_State IN ('') OR
PhisicalAddress_Zip IN ('');
我正在寻找的是AND所以我只获得匹配Status [Lead,Customer]和SalesRep [cary]的记录
SELECT id, `ContactID`, Status, SalesRep, LeadSource, `PhysicalAddress_State`, `PhisicalAddress_Zip` FROM Contacts WHERE
Status IN ('Lead','customer') AND
SalesRep IN('cary') AND
LeadSource IN ('') AND
PhysicalAddress_State IN ('') AND
PhisicalAddress_Zip IN ('');
但是,如果我将OR更改为AND,除非每个字段都有选择,否则我不会获得任何记录。如果我没有搜索值,我怎样才能让AND工作?
答案 0 :(得分:0)
我能够找到一种不在WHERE中包含字段的方法,这就是我想出的:
SELECT id, `ContactID`, Status, SalesRep, LeadSource, `PhysicalAddress_State`, `PhisicalAddress_Zip` FROM Contacts WHERE
IF(true, Status IN ('Closed'), id != 0) AND
IF(true, SalesRep IN('Cary'), id != 0) AND
IF(false, LeadSource IN (''), id != 0) AND
IF(false, PhysicalAddress_State IN (''), id != 0) AND
IF(true, PhisicalAddress_Zip IN ('87123'), id != 0);
对于我的环境:
SELECT id, `ContactID`, Status, SalesRep, LeadSource, `PhysicalAddress_State`, `PhisicalAddress_Zip` FROM Contacts WHERE
IF(:includeStatus, Status IN :status, id != 0) AND
IF(:includeSalesRep, SalesRep IN :SalesRep, id != 0) AND
IF(:includeLeadSource, LeadSource IN :LeadSource, id != 0) AND
IF(:includePhysicalAddress_State, PhysicalAddress_State IN :PhysicalAddress_State, id != 0) AND
IF(:includePhisicalAddress_Zip, PhisicalAddress_Zip IN :PhisicalAddress_Zip, id != 0);
感谢您的建议!