根据第3个映射表从2个表中选择记录

时间:2017-03-24 11:45:12

标签: sql sql-server

我有3张以下结构的表格 公司 - 表1

Id  
Name  
Phone

联络 - 表2

Id  
FirstName  
LastName  
CellPhone  
Phone  
Phone2  
Email1

Company_Contact - 表3

CompanyId  
ContactId

一家公司可以拥有多个联系人。现在我想选择 Contact.FirstName,Contact.LastName,Company.Name,Contact.CellPhone,Contact.Phone,Contact.Phone2,Company.Phone,Contact.Email1 for all companies

3 个答案:

答案 0 :(得分:1)

您需要简单的加入

select Contact.FirstName, Contact.LastName, Company.Name, Contact.CellPhone, Contact.Phone, Contact.Phone2, Company.Phone, Contact.Email1 
from Company 
inner join Company_Contact on Company.id = Company_Contact.CompanyId  
inner join Contact on Contact.id = Company_Contact.ContactId

答案 1 :(得分:1)

首先,你需要知道你想要选择的字段,并将它们联系起来

SELECT Contact.FirstName, Contact.LastName, Company.Name, Contact.CellPhone,
Contact.Phone, Contact.Phone2, Company.Phone, Contact.Email1 
FROM contact, company, company_contact 
WHERE company.id = Company_Contact.companyId and contact.id = company_contact.contactId

我认为这就是你想要的 也许有错误,但这是问题的逻辑

答案 2 :(得分:0)

这样的东西
SELECT Contact.FirstName, Contact.LastName, Company.Name, Contact.CellPhone, Contact.Phone, Contact.Phone2, Company.Phone, Contact.Email1  
FROM Company, Contact, Company_Contact 
WHERE Company_Contact.CompanyId = Company.Id AND Company_Contact.ContactId = Contact.Id