使用INNER JOIN从多个表中查询SQL

时间:2013-07-30 07:31:30

标签: sql sql-server

我有一个名为INVOICE的表来自Where get ADDRESSID

我有另一个名为Address as

的表
ADDRESSID         ADDRESS
2                 BB
2                 BC

CC和BC的值在另一个名为ADDRESSVALUE的表中,基于ADDRESSID

ID      CODE    VALUE
1        BB      BlindFold
2        BC      Bucharest

现在我使用内部联接查询表格

SELECT AC.VALUE AS ADDRESS 
FROM ADDRESS AS OT
INNER JOIN INVOICE AS OM ON  OM.ADDRESSID = OT.ADDRESSID
INNER JOIN ADDRESSVALUE AS AC ON OT.ADDRESS = AC.CODE
WHERE OM.ADDRESSID = 2

我的结果为

Blindfold
Blindfold

但它应该是

BlindFold
Bucharest

4 个答案:

答案 0 :(得分:1)

(更新)获得您正在寻找的结果的一种方法:

SELECT AC.VALUE AS ADDRESS 
FROM ADDRESS AS OT
INNER JOIN INVOICE AS OM ON  OM.ADDRESSID = OT.ADDRESSID
INNER JOIN ADDRESSVALUE AS AC ON OT.ADDRESS = AC.CODE
WHERE OM.ADDRESSID = @AddressID

SQLFiddle here

答案 1 :(得分:0)

直接使用,无需加入!

SELECT OM.VALUE AS ADDRESS 
FROM INVOICE AS OM WHERE OM.ADDRESSID = @AddressID

-

SELECT value FROM second_table WHERE code IN
(SELECT address FROM first_table WHERE addressid = @AddressID);

答案 2 :(得分:0)

如果Address和Addressvalue表应该通过两个表中存在的列ADDRESSID联合,那么你的select语句应该包含类似的内容

ADDRESS.ADDRESSID = ADDRESSVALUE.ADDRESSID

答案 3 :(得分:0)

试试这个

SELECT C.VALUE AS ADDRESS
FROM ADDRESS A
INNER JOIN INVOICE B ON A.ADDRESSID=B.ADDRESSID
INNER JOIN ADDRESSVALUE C ON A.ADDRESSID=C.ADDRESSID 
    AND A.ADDRESS=C.CODE
WHERE B.ADDRESSID=2

例如,您可以看到SQLFiddle