我有这个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"
简单地说,我有以下表格:
因此,只需将主键和外键链接在一起,即可获得与“paidinvoiceid”对应的require字段,该字段具有分配给它的提供者。
请帮忙。谢谢!
答案 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”开始工作,例如:
所以你很快就会找到排除行的位置。