SQL:连接两个表,其中列为null

时间:2012-11-09 19:05:20

标签: mysql sql

我正在使用mysql数据库。我有两个表错误和配置文件。 Bugs表有两列(assigned_to,qa_contact),通过多对一关系指向配置文件。 这些是我查询的简化版本。

首先,我试图这样做,但它返回重复的行,其中qa_contact在错误表中为空

select 
  bug_id, 
  desc, 
  dev.assigned_to, 
  qa.qa_contact 
from 
 bugs, 
 profiles as dev, 
 profiles as qa
where 
  assigned_to = dev.userid 
  and (qa_contact = qa.userid or qa_contact is null)

其次,我的新方法是:

select bug_id, desc, dev.assigned_to, qa.qa_contact 
from 
 bugs, 
 profiles as dev, 
 profiles as qa
where 
  assigned_to = dev.userid 
  and qa_contact = qa.userid

 UNION

select bug_id, desc, dev.assigned_to, null 
from 
 bugs, 
 profiles as dev, 
 profiles as qa
where 
  assigned_to = dev.userid 
  and qa_contact is null

但在第二种方法中,它排除了qa_contact为null的结果。任何人都可以建议一种有效的方法,因为我处理数百万的记录,并希望在结果集上添加更多的过滤器。

2 个答案:

答案 0 :(得分:7)

这是LEFT JOIN的用途:

SELECT bug_id, `desc`, dev.assigned_to, qa.qa_contact 
FROM bugs
INNER JOIN profiles as dev ON bugs.assigned_to = dev.userid
LEFT OUTER JOIN profiles as qa ON bugs.qa_contact = qa.userid

答案 1 :(得分:2)

我想你想使用LEFT JOIN

select bug_id, desc, dev.assigned_to, qa.qa_contact 
from bugs b
left join profiles dev
  b.assigned_to dev.userid
left join profiles qa
  on b.qa_contact = qa.userid

如果您需要帮助学习JOIN语法,那么这里有一个很棒的visual explanation of joins

即使LEFT JOIN表中不存在id,bugs也会返回profiles表中的数据。

相关问题