SQL Server连接和where语句不起作用

时间:2010-07-28 08:37:15

标签: sql sql-server

我有这个SQL Server语句,我不确定为什么它没有返回任何记录:

SELECT 
    contacts.firstname , 
    contacts.lastname , 
    contacts.address1 , 
    contacts.city, 
    contacts.zip, 
    countries.title AS countrytitle, 
    states.title AS statetitle 
FROM providers, payableinvoices, contacts 
LEFT JOIN countries ON countries.countryid=contacts.countryid 
LEFT JOIN states ON states.stateid=contacts.stateid 
WHERE payableinvoices.payableinvoiceid=4 
AND providers.providerid=payableinvoices.providerid 
AND providers.contactid=contacts.contactid"

简单地说,我有以下表格:

  • 联系人表:其列包括contactid,firstname,lastname,address1,city,zip
  • providers表:其列包括providerid,contactid
  • paidinvoices表:其列包括paidinvoiceid,providerid

因此,只需将主键和外键链接在一起,即可获得与“paidinvoiceid”对应的require字段,该字段具有分配给它的提供者。

请帮忙。谢谢!

2 个答案:

答案 0 :(得分:1)

尝试使用:

SELECT 
    C.FirstName , 
    C.LastName , 
    C.Address1 , 
    C.City, 
    C.Zip, 
    CO.Title AS CountryTitle, 
    S.Title AS StateTitle 
FROM Contacts C
INNER JOIN Providers P ON P.ContactID = C.ContactID
INNER JOIN PayableInvoices PI ON PI.ContactID = P.ContactID
LEFT JOIN Countries CO ON CO.CountryID = C.CountryID 
LEFT JOIN States S ON S.StateID = C.StateID
WHERE PI.PayableInvoiceID = 4 

答案 1 :(得分:1)

我要做的第一件事是标准化以使用整个连接:

SELECT 
    contacts.firstname , 
    contacts.lastname , 
    contacts.address1 , 
    contacts.city, 
    contacts.zip, 
    countries.title AS countrytitle, 
    states.title AS statetitle 
FROM providers
    INNER JOIN payableinvoices ON providers.providerid=payableinvoices.providerid 
    INNER JOIN contacts ON providers.contactid=contacts.contactid
    LEFT JOIN countries ON countries.countryid=contacts.countryid 
    LEFT JOIN states ON states.stateid=contacts.stateid 
WHERE payableinvoices.payableinvoiceid=4 

以上看起来很好。

如果你没有得到你想要的行,你需要从基本的“SELECT ... FROM providers”开始工作,例如:

  • 从基本的“SELECT .... FROM providers”
  • 开始
  • 将INNER JOIN添加到应付款发票中......测试
  • 添加WHERE条件...测试 等等。

所以你很快就会找到排除行的位置。