如何一次从多个表中选择多个记录

时间:2010-05-22 22:52:44

标签: c# .net sql-server winforms tsql

我有两个表,Customer和CustomerPhone。客户通常有多个电话号码,因此当我在客户101上运行select语句时,由于多个电话号码,我将获得多条记录。

所有“电话”和“传真”字段都属于CustomerPhone表。这些被视为CustomerPhone表中的两个记录,而其余字段与Customer表相关,后者是单个记录。

在这种情况下,如何填写“电话和传真”字段?我应该首先在CustomerPhone上运行select语句,然后在客户上运行select语句吗?

1 个答案:

答案 0 :(得分:2)

我猜你的CustomerPhone表看起来像

CustomerPhone
CustomerID int
Number varchar
PhoneType   phone | fax

UI似乎只允许一个普通电话和传真号码。如果是这种情况,并且客户最多只有一部电话,一部传真(但可能没有),即CustomerPhone中CustomerID / PhoneType上的唯一索引,那么您可以将所有信息检索为一个查询:

SELECT c.*, phone.Number, fax.Number FROM Customer c 
LEFT JOIN CustomerPhone phone ON phone.CustomerID=c.CustomerID
LEFT JOIN CustomerPhone fax = fax.CustomerID=c.CustomerID
相关问题