MySQL:包含两个表和第三个相关表的复杂连接语句

时间:2010-05-11 21:52:43

标签: mysql select outer-join correlation

我有两个为两个不同系统构建的表。我在一个表(称为“潜在客户”)中有记录代表客户,而记录在另一个表(称为“经理”)中,它们是完全相同的客户,但“经理”使用不同的字段

(例如,“leads”包含一个电子邮件地址,“manager”包含两个不同电子邮件的两个字段 - 其中任何一个可能是来自“lead”的电子邮件)。

所以,我创建了一个包含lead_id和manager_id的关联表。目前这个相关表是空的。

我正在尝试查询“潜在客户”表格,以便为我提供与“经理”电子邮件字段和单个“潜在客户”电子邮件字段匹配的记录,同时忽略已添加到“相关的“表格。 (这样我就可以看到有多少匹配的引线尚未相关。)这是我当前的无效SQL尝试:

SELECT leads.id, manager.id
  FROM leads, manager
  LEFT OUTER JOIN correlation ON correlation.lead_id = leads.id
  WHERE correlation.id IS NULL
  AND leads.project != "someproject"
  AND (manager.orig_email = leads.email OR manager.dest_email = leads.email)
  AND leads.created BETWEEN '1999-01-01 00:00:00' AND '2010-05-10 23:59:59'
  ORDER BY leads.created ASC;

我收到错误:'on clause'

中的未知列'leads.id'

在你想知道之前:“lead”表中有记录,其中leads.project!=“someproject”和leads.created落在这些日期之间。为了完整性,我已经包含了这些额外的参数。

1 个答案:

答案 0 :(得分:2)

您的表格列出了错误的方式,因此LEFT OUTER JOIN正在按照您的意图将manager加入correlation而不是leads加入correlation。尝试将它们交换成圆形:

SELECT leads.id, manager.id
  FROM manager, leads
  LEFT OUTER JOIN correlation ON correlation.lead_id = leads.id
  WHERE correlation.id IS NULL
  AND leads.project != "someproject"
  AND (manager.orig_email = leads.email OR manager.dest_email = leads.email)
  AND leads.created BETWEEN '1999-01-01 00:00:00' AND '2010-05-10 23:59:59'
  ORDER BY leads.created ASC;

一般情况下,我建议不要混合旧式和新式连接,以避免这种类型的错误。我更愿意看到这样的事情:

SELECT leads.id, manager.id
  FROM leads
  LEFT OUTER JOIN correlation ON correlation.lead_id = leads.id
  JOIN manager ON manager.orig_email = leads.email OR manager.dest_email = leads.email
  WHERE correlation.id IS NULL
  AND leads.project != "someproject"
  AND leads.created BETWEEN '1999-01-01 00:00:00' AND '2010-05-10 23:59:59'
  ORDER BY leads.created ASC;