Mysql WHERE子句中的IF条件

Mysql WHERE子句中的IF条件,mysql,sql,Mysql,Sql,我有一个问题: select p.id AS id, p.text AS text, p.date AS date, k.color AS color, ... FROM cform_mba_contacts p, cform_mba_contacts_category_links o, cform_mba_contacts_status k, ... where p.id_peoples = ".$this->id." AND o.id_contacts = p.id AND o

我有一个问题:

select
p.id AS id,
p.text AS text,
p.date AS date,
k.color AS color,
...

FROM

cform_mba_contacts p,
cform_mba_contacts_category_links o,
cform_mba_contacts_status k,
...

where

p.id_peoples = ".$this->id." AND
o.id_contacts = p.id AND
o.id_status = k.id AND
...

order by p.date
在引入新条件之前,此查询工作正常。我需要选择具有该条件的数据,并且仅使用
p.id\u>。$this->id.“
。我尝试使用
联合
,但没有成功。我该怎么做

更新


我通过阅读有关UNION运算符的其他文档来解决问题
顺序子句不需要使用p.date,而只需要使用date,在第二条语句中需要选择第一条语句中选择的列的计数

WHERE 1 = 1
AND (@id IS NULL 
     OR 
     ( p.id_peoples = @id  
       AND o.id_contacts = p.id 
       AND o.id_status = k.id
     ))

ORDER BY p.date
其中,
@id
是通过
$this->id.
传递的参数


只有当通过
$this->id.
传递的参数不为空时,才会应用条件
o.id\u contacts=p.id和o.id\u status=k.id

可能您想要的是联合所有人

尝试以下操作:

WHERE  p.id_peoples <> ".$this->id." 
       OR ( o.id_contacts = p.id AND
            o.id_status = k.id AND
            ...
          )
其中p.id\u人民“$this->id”
或(o.id_触点=p.id和
o、 id_状态=k.id和
...
)

您的问题或查询要求到底是什么??您编写的@id为NULL,但随后。$this->id.不为NULL这怎么可能?)在不同的条件下给我一个error@user1506183
WHERE
子句中的
块可以分为两部分,第一部分是
@id为NULL
如果为false,则整个
条件将不会在那里执行,因此
WHERE
子句将是
其中1=1,即,无where子句。如果为真,则执行
块。这是我从你的问题中了解到的。那不是你要求的行为吗?您犯了什么错误?我通过阅读有关UNION运算符的其他文档来解决我的问题,谢谢man@user1506183不客气。我只是想帮你,很高兴听到你的问题解决了(诸如此类的事),但我用了工会。我通过阅读关于UNION运算符的其他文档来解决我的问题,谢谢我通过阅读关于UNION运算符的其他文档来解决我的问题,thanks@user1506183美好的你应该张贴你的答案。所以其他人也可以从中得到帮助。
create a string and execute the string at the last.

decalre @thequery varchar(max);
 set @thequery ='select * from emp'
if (1=1)
begin
set @thequery = @thequery + ' where emp_id =1'
end
else
begin
set @thequery = @thequery + ' where emp_id=0'
 end exec("@thequery ");