如何正确加入这些选择?

时间:2013-02-07 23:04:37

标签: sql sql-server-2012

[1] SELECT X.id FROM somwhere WHERE X.location = _stringReturnedFromC#_
            // I need ID from this table, I only know strin: Location (from C#)

[2] SELECT Y.NameID FROM _relationBetweenXandY_ xy WHERE xy.ID = [1]
           // I use the ID I just found in [1]

[3] SELECT Z.Name FROM Z WHERE Z.NameID = [2]
           // I use the ID I found in [2]

现在我如何告诉select [2]我正在寻找xy.ID = result from select [1]

select [3]我正在寻找ID为Z.NameID

的人的名字

我问了这个问题here,但就我而言,这个问题无法挽救。

Z table: 
      Z.Name, Z.NameID
Y Table: 
      Y.PLACE, Y.PlaceID // fixed, Used to be PlaceID, is inface string: Place
X Table:
      X.Name, X.PlaceID

如果它们具有相同的名称,则它们是外键(NameID,PlaceID)

这是实际代码的样子:

SELECT * FROM Angajati a
JOIN Distribuire d ON d.Locatie = 'Oradea'
// now I need to get d.DistribuireID while I know d.Locatie (d.location). How ?
JOIN Angajari an ON d.DistribuireID = an.DistribuireID

因此

SELECT *
FROM TableX X 
   JOIN TableY y on x.PlaceId = y.PlaceId
   JOIN TableZ z on y.NameId = z.NameId

不起作用,因为我不知道Y.PlaceID,我只知道Y.Place

最后编辑

对不起,如果这太长了。这是它应该是什么样子(我的意思是,即使语法不起作用,这也是逻辑)现在我只需要这个语法!

SELECT d.DistribuireID FROM Distribuire d WHERE d.Locatie = 'Oradea'
JOIN Angajari an ON an.DistribuireID = d.DistribuireID /*Here I'd need an.AngajatID for the locationID I just selected*/
JOIN Angajati a ON a.AngajatID = an.AngajatID

1 个答案:

答案 0 :(得分:2)

看起来你只需要一些INNER JOIN:

SELECT *
FROM TableX X 
   JOIN TableY y on x.PlaceId = y.PlaceId
   JOIN TableZ z on y.NameId = z.NameId

希望这有帮助。

-EDIT - 为什么这不起作用?对不起,如果我不理解你的问题...

SELECT d.DistribuireID 
FROM Distribuire d 
   JOIN Angajari an ON an.DistribuireID = d.DistribuireID
   JOIN Angajati a ON a.AngajatID = an.AngajatID
WHERE d.Locatie = 'Oradea'
祝你好运。