SQL从两个链接表中选择

时间:2015-06-01 22:25:29

标签: mysql sql

我在MySQL中有两个表,customercontacts

customer中的每一行可以在contacts中有多行,contacts.company将等于customer.sequence

如何运行查询来搜索两个表并仅返回customer表中的结果?

例如,如果我有这个数据:

customer:

sequence = 123
company = Company A

sequence = 321
company = Company B

contacts:

company = 123
forename = John

company = 123
forename = Steve

company = 321
forename = Joe

company = 321
forename = Andy

company = 321
forename = John

我搜索安迪 - 它应该返回Company A

如果我搜索John,则应该返回Company ACompany B

1 个答案:

答案 0 :(得分:0)

select
    C.Company
from
    Customer,
    Contacts
where
    Customer.Sequence = Contacts.Company
    and Contacts.Forename = '<your search name goes here>'