我有一个当前使用的SQL查询,它将一个报表的3个表连接在一起。我需要将第四个表中的数据附加到这个表中。
下面是我当前的查询,运行良好:
SELECT `contact_id`,`account_id`,`last_name`,`first_name`,`name`,`phone_work`,`billing_address_street`,`billing_address_postalcode`,`phone_office`
FROM `crm`.`contacts`
LEFT JOIN `crm`.`accounts_contacts` ON `crm`.`contacts`.`id`=`crm`.`accounts_contacts`.`contact_id`
LEFT JOIN `crm`.`accounts` ON `crm`.`accounts_contacts`.`account_id`=`crm`.`accounts`.`id`下面是我试图更新的查询,以便从第四个表中引入电子邮件的附加字段:
SELECT `contact_id`,`account_id`,`last_name`,`first_name`,`name`,`phone_work`,`billing_address_street`,`billing_address_postalcode`,`phone_office`,`email_address`
FROM `crm`.`contacts`
LEFT JOIN `crm`.`accounts_contacts` ON `crm`.`contacts`.`id`=`crm`.`accounts_contacts`.`contact_id`
LEFT JOIN `crm`.`accounts` ON `crm`.`accounts_contacts`.`account_id`=`crm`.`accounts`.`id`
LEFT JOIN `crm`.`email_addresses` ON `crm`.`accounts_contacts`.`contact_id`=`crm`.`email_addresses`.`id`查询运行时没有出现错误,但是email_address列中填充了空值。
以下是每个表的字段:
`accounts_contacts`
id
contact_id
account_id
`email_addresses`
id
email_address有人知道我哪里出问题了吗?如果我遗漏了任何必要的信息,让我知道,我会编辑它。
额外信息:
结果发现,我的联系人和他们的电子邮件地址之间缺少一个链接。我创建了一个测试用户来调查这个问题,这就是我所发现的:
首先,我发现了我的新用户的联系方式:
`crm`.`contacts`.`id` = bf3259ec-65eb-1e65-efd1-51669e45cdb0然后我发现一张桌子上有这个id:
SELECT * FROM `crm`.`email_addr_bean_rel` WHERE bean_id = "bf3259ec-65eb-1e65-efd1-51669e45cdb0"这返回了一个email_address_id
c3e14c9e-b6bc-b2d0-6dbf-51669e83bff4这链接到crm.email_addresses.id
发布于 2015-04-16 11:50:32
如果使用表别名,则查询更容易阅读:
SELECT`contact_id`, `account_id`, `last_name`, `first_name`, `name`, `phone_work`,
`billing_address_street`, `billing_address_postalcode`, `phone_office`,
`email_address`
FROM `crm`.`contacts` c LEFT JOIN
`crm`.`accounts_contacts` ac
ON c.`id` = ac.`contact_id` LEFT JOIN
`crm`.`accounts` a
ON ac.`account_id` = a.`id` LEFT JOIN
`crm`.`email_addresses` ea
ON ac.`contact_id` = ea.`id`在contact_id中,account_contacts中没有与email_address.id匹配的值。这可能是:
如果我不得不猜的话,那将是最后一次了。根据其他表所使用的命名约定,我希望在某个地方有一个名为email_address_id的列。
https://stackoverflow.com/questions/29673720
复制相似问题