我的SQL内部连接使用两个条件的表,具体取决于另一列的值

时间:2016-07-03 18:17:32

标签: mysql

我有两个表user_profile,chat_friendlist返回

chat_friendslist and user_profile table

SELECT a.id, a.user_id, a.friend_id, 
IF(a.user_id=146, e.user_id, d.user_id) as conversation_user_id,   
IF(a.user_id=146, e.first_name, d.first_name) as conversation_first_name,   
IF(a.user_id=146, e.last_name, d.last_name) as conversation_last_name  
FROM chat_friendlist a   
inner join user_profile as d on a.user_id = d.user_id  
inner join user_profile as e on a.friend_id = e.user_id  
where (a.user_id = 146 or a.friend_id=146) and a.status='accepted'

The Results of above query

我收到了这个结果

但现在我想用名字和姓氏添加另一个条件搜索。

结果应按名字和姓氏过滤。

我尝试过以下查询

SELECT a.id, a.user_id, a.friend_id,  
IF(a.user_id=146, e.user_id, d.user_id) as conversation_user_id,   
IF(a.user_id=146, e.first_name, d.first_name) as conversation_first_name,   
IF(a.user_id=146, e.last_name, d.last_name) as conversation_last_name  
FROM chat_friendlist a   
inner join user_profile as d on a.user_id = d.user_id  
inner join user_profile as e on a.friend_id = e.user_id  
where (a.user_id = 146 or a.friend_id=146) and a.status='accepted'   
and d.first_name like '%g%' and e.first_name like '%g%'  

但它什么也没有回报。

请帮帮我

2 个答案:

答案 0 :(得分:0)

尝试使用此

(d.first_name like '%g%' or e.first_name like '%g%')

答案 1 :(得分:0)

你可以写

SELECT a.*,  
IF(a.user_id=146, e.user_id, d.user_id) as conversation_user_id,   
IF(a.user_id=146, e.first_name, d.first_name) as conversation_first_name,   
IF(a.user_id=146, e.last_name, d.last_name) as conversation_last_name  
FROM chat_friendlist a   
inner join user_profile as d on a.user_id = d.user_id  
inner join user_profile as e on a.friend_id = e.user_id  
where (a.user_id = 146 or a.friend_id=146) and a.status='accepted'   
and (d.first_name like '%G%' and e.first_name like '%G%')  

这可能是工作