内连接中的OR运算符

时间:2015-07-23 17:55:37

标签: sql subquery inner-join

我有疑问。

SELECT  VendorID,VendorName,VendorType,FirstName,LastName,
  VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo ,Photo,VendorNotes FROM 
  Vendor inner JOIN VendorTypeTable ON Vendor.VendorTypeID=VendorTypeTable.VendorTypeID

现在另一方面,我想检索那些VendorTypeID为null的供应商,就像这个查询一样。

SELECT  VendorID,VendorName,FirstName,LastName,
 VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo ,Photo,VendorNotes FROM 
Vendor WHERE VendorTypeID IS NULL;

我如何结合这两个查询。

3 个答案:

答案 0 :(得分:0)

像这样的东西

SELECT vendorid, 
       vendorname, 
       vendortype, 
       firstname, 
       lastname, 
       vendorcompany, 
       contact, 
       phone, 
       altcontact, 
       email, 
       openingbalance, 
       openingdate, 
       vendoraccountno, 
       photo, 
       vendornotes 
FROM   vendor 
       INNER JOIN vendortypetable 
               ON vendor.vendortypeid = vendortypetable.vendortypeid 
                   OR vendor.vendortypeid IS NULL 

答案 1 :(得分:0)

你也可以像这样使用左外连接

SELECT vendorid, 
       vendorname, 
       vendortype, 
       firstname, 
       lastname, 
       vendorcompany, 
       contact, 
       phone, 
       altcontact, 
       email, 
       openingbalance, 
       openingdate, 
       vendoraccountno, 
       photo, 
       vendornotes 
FROM   vendor 
       left outer JOIN vendortypetable 
               ON vendor.vendortypeid = vendortypetable.vendortypeid 

答案 2 :(得分:0)

虽然@Fireblade是绝对正确的,但如果有两个查询返回相同的字段,有时UNION是正确的答案。这允许您独立调整每个的性能。

SELECT  VendorID,VendorName,VendorType,FirstName,LastName,  
VendorCompany,Contact,Phone,AltContact,Email,
OpeningBalance,OpeningDate,VendorAccountNo ,Photo,VendorNotes FROM 
Vendor inner JOIN VendorTypeTable ON 
Vendor.VendorTypeID=VendorTypeTable.VendorTypeID
UNION
SELECT  VendorID,VendorName,FirstName,LastName, VendorCompany,
Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,
VendorAccountNo ,Photo,VendorNotes FROM 
Vendor WHERE VendorTypeID IS NULL;