mysql在同一个表上多次连接

时间:2013-05-31 09:37:44

标签: mysql join sugarcrm

我有两个数据库,每个数据库都有联系人表。我想从冗余数据库中找出主数据库中存在哪些联系人。主要数据库是sugarcrm。我想要多余的是hdb。我有以下查询无法正常工作

SELECT c.id, c.first_name, c.last_name
from `sugarcrm`.`contacts` c
left join `hdb`.`contacts` as cl
    ON cl.lastname = c.last_name
left join `hdb`.`contacts` as cf
    on cf.firstname = c.first_name

limit 0, 10000

我在sugacrm.contacts中总共有10187条记录,在hdb.contatcs中总共有8619条记录。

我试过这个

SELECT c.id, c.first_name, c.last_name
from `sugarcrm`.`contacts` c
where not exists
(select * from `hdb`.`contacts`
where firstname != first_name and lastname != last_name
)
limit 0, 10000

返回14条记录

我想要包含与电子邮件地址的比较,但我的查询无效。链接sugarcrm中的电子邮件地址如下

email_address表有id email_addr_bean_rel有电子邮件ID和联系人ID

SELECT 
    c.id, 
    c.first_name, 
    c.last_name
FROM `sugarcrm`.`contacts` c, `sugarcrm`.`email_addresses` e, `sugarcrm`.`email_addr_bean_rel` er
LEFT JOIN `hdb`.`contacts` as cl
    ON cl.lastname = c.last_name
    AND cl.firstname = c.first_name
    AND cl.email = e.email_address
inner join `sugarcrm`.`contacts` 
    on er.bean_id = `sugarcrm`.`contacts`.id
inner join `sugarcrm`.`email_addr_bean_rel`
    on e.id = er.email_address_id

limit 0,100000

我决定使用电子邮件管理,以使用navicat获取以下内容

    SELECT
sugarcrm.email_addresses.email_address
FROM
sugarcrm.contacts
INNER JOIN sugarcrm.email_addr_bean_rel ON sugarcrm.contacts.id = sugarcrm.email_addr_bean_rel.bean_id
INNER JOIN sugarcrm.email_addresses ON sugarcrm.email_addresses.id = sugarcrm.email_addr_bean_rel.email_address_id
INNER JOIN hdb.contacts ON sugarcrm.email_addresses.email_address = hdb.contacts.EMAIL
LIMIT 0, 100000

3 个答案:

答案 0 :(得分:1)

更新:要检查哪些联系人在主数据库中而不在辅助数据库中,请尝试以下操作:

SELECT 
    c.id, 
    c.first_name, 
    c.last_name
FROM `sugarcrm`.`contacts` c
LEFT JOIN `hdb`.`contacts` as cl
    ON cl.lastname = c.last_name
    AND cl.firstname = c.first_name
WHERE
    cl.lastname IS NULL

但是:

  • 你应该使用id(如果有的话)加入2个字符串列

UPDATE2:回答“如何更改电子邮件查询以显示来自hdb的联系人,这些联系人在sugarcrm中不存在?”

SELECT
    hdb.*
FROM
    hdb.contacts
LEFT JOIN sugarcrm.email_addresses 
    ON sugarcrm.email_addresses.email_address = hdb.contacts.EMAIL
LEFT JOIN sugarcrm.email_addr_bean_rel 
    ON sugarcrm.email_addr_bean_rel.bean_id = sugarcrm.email_addresses.id
LEFT JOIN sugarcrm.contacts
    ON sugarcrm.contacts.id = sugarcrm.email_addr_bean_rel.bean_id
WHERE
    sugarcrm.contacts.id IS NULL
LIMIT 0, 100000

答案 1 :(得分:0)

你可以试试这个,

SELECT 
     c.id, c.first_name, c.last_name
from 
    `sugarcrm`.`contacts` c
where
     c.id in (select c1.id from `hdb`.`contacts` c1)

这会给出sugarcrm db

中的记录

答案 2 :(得分:0)

要在hdb中查找sugarcm中不存在的用户,请尝试:

SELECT ch.id, ch.first_name, ch.last_name
from `hdb`.`contacts` ch
left join `sugarcrm`.`contacts` as cs
       ON ch.lastname = cs.last_name and cl.firstname = cs.first_name
where cs.first_name is null