加入两个表,结果两次得到结果

时间:2012-09-07 15:40:19

标签: sql join

我的查询中有一个select命令,用于从两个表中获取数据,结果的每一行结果都是两次,我的查询是

Select  
  Driver.DriverID,
  Driver.FName,
  Driver.LName,
  Driver.SmartCardNumber,
  Driver.DriverState,
  Driver.DriverCity,
  Driver.DriverAddress,
  Driver.Mobile,
  Driver.Telephone,
  Driver.MelliCardNumber, 
  Driver.CertificatePublisher,
  Driver.addeddate,
  Driver.ContractorID,
  Driver.editeddate,
  Contractor.name  
From Driver,Contractor

4 个答案:

答案 0 :(得分:3)

如果驾驶员和承包商表之间存在关系,则需要条件。

类似

Select  
  Driver.DriverID,
  Driver.FName,
  Driver.LName,
  Driver.SmartCardNumber,
  Driver.DriverState,
  Driver.DriverCity,
  Driver.DriverAddress,
  Driver.Mobile,
  Driver.Telephone,
  Driver.MelliCardNumber, 
  Driver.CertificatePublisher,
  Driver.addeddate,
  Driver.ContractorID,
  Driver.editeddate,
  Contractor.name  
From Driver,Contractor
    where Driver.ContractorID = Contractor.id

假设ContractorID链接到承包商的ID。

答案 1 :(得分:0)

您可以尝试使用DISTINCT。

SELECT DISTINCT  Driver.DriverID,
Driver.FName,
Driver.LName,
Driver.SmartCardNumber,
Driver.DriverState,
Driver.DriverCity,
Driver.DriverAddress,
Driver.Mobile,
Driver.Telephone,
Driver.MelliCardNumber,
Driver.CertificatePublisher,
Driver.addeddate,
Driver.ContractorID,
Driver.editeddate,
Contractor.name  

From Driver,Contractor

或者,如果您不需要CROSS结果,那么如果您在两个表之间有引用,则可以尝试进行LEFT或INNER JOIN

答案 2 :(得分:0)

您需要告诉dbms如何连接2个表中的记录:

例如

Select 
  Driver.DriverID,
  Driver.FName,
  ...,
  Contractor.name  
  From Driver,Contractor
  Where Driver.ContractorID = Contractor.ID;

Select 
  Driver.DriverID,
  Driver.FName,
  ...,
  Contractor.name  
  From Driver inner join Contractor
  On Driver.ContractorID = Contractor.ID;

答案 3 :(得分:0)

Select  Driver.DriverID,
Driver.FName,
Driver.LName,
Driver.SmartCardNumber,
Driver.DriverState,
Driver.DriverCity,
Driver.DriverAddress,
Driver.Mobile,
Driver.Telephone,
Driver.MelliCardNumber,
Driver.CertificatePublisher,
Driver.addeddate,
Driver.ContractorID,
Driver.editeddate,
Contractor.name  
From Driver,Contractor
where Driver.DriverId=Contractor.DriverId;

(提到这样的条件来获取数据)