提问者:小点点

MySQL:Where子句基于IF语句的结果?


下面是查询:

select IF ((t1.emp_id IS NOT NULL), t2.username, '') 
from t1, t2 
where t1.user_id = "285" AND t2.id = t1.emp_id

它工作得很好,但是如果t1.emp_id为NULL,它将不会返回结果,因为这部分和t2.id=t1.emp_id,但是这部分保证了我,如果t1.emp_id不为NULL,我将得到精确的t2.id。 有办法处理吗?

其思想是,如果t1.emp_id不为空,则基于关系t1.emp_id=t2.id返回t2.username,但在本例中,当t1.emp_id为空时,由于查询的最后一部分,它不会返回结果。 如果我删除最后一部分,它将不会返回我从T2的确切行。


共2个答案

匿名用户

我认为您需要一个左联接。 我最好的猜测是:

select coalesce(t2.username, '')
from t1 left join
     t2 
     on t2.id = t1.emp_id 
where t1.user_id = 285;

匿名用户

使用以下查询(&R 再试试。

select t1.emp_id, t2.username
from t1, t2 
where t1.user_id = "285" AND t2.id = t1.emp_id AND t1.emp_id is NOT NULL;