SQL Server 2005加入问题

时间:2013-01-18 09:04:18

标签: sql sql-server sql-server-2005 select

我有以下3个数据表

Options Table
UID (pk) SID (pk) TID (pk)
--------------------------
1        20       2
1        20       3
1        13       3
1        14       4

Types Table
TID (pk) TText
--------------------------
1        Text 1
2        Text 2
3        Text 3
4        Text 4

Sets Table
SID (pk)  SText
--------------------------
13        Set 13
14        Set 14
20        Set 20

我试图得到如下输出,只有4行来自options表,但是来自其他2个表的相应文本。我的加入似乎已经过了。

我想要的结果是:

UID (pk) SID (pk) TID (pk)  SText      TText
------------------------------------------------------
1        20       2         Set 20     Text 2
1        20       3         Set 20     Text 3
1        13       3         Set 13     Text 3
1        14       4         Set 14     Text 4

3 个答案:

答案 0 :(得分:1)

SELECT  a.*, b.Stext, c.TText
FROM    Options a
        INNER JOIN Sets b
            ON a.SID = b.SID
        INNER JOIN  Types c
            ON a.TID = c.TID

更新1

添加DISTINCT

SELECT  DISTINCT a.*, b.Stext, c.TText
FROM    Options a
        INNER JOIN Sets b
            ON a.SID = b.SID
        INNER JOIN  Types c
            ON a.TID = c.TID

答案 1 :(得分:0)

SELECT O.UID,O.SID,O.TID,T.TText,S.SText
FROM Options O
INNER JOIN Types T ON
    T.TID = O.TID
INNER JOIN Sets S ON
    S.SID = O.SID

答案 2 :(得分:0)

你可以试试这个:

SQLFIDDLE DEMO

编辑:对于sql server使用distinct,因为第一个查询是用mysql编写的

select distinct o.*, t.ttext, s.stext from 
    options o
    inner join 
    types t
    on o.tid = t.tid
    left join 
    sets s
    on s.sid = o.sid
    ;

select o.*, t.ttext, s.stext from 
options o
inner join 
types t
on o.tid = t.tid
left join 
sets s
on s.sid = o.sid
group by o.uid, o.tid, o.sid
;

| UID | SID | TID |  TTEXT |  STEXT |
-------------------------------------
|   1 |  20 |   2 | Text 2 | Set 20 |
|   1 |  13 |   3 | Text 3 | Set 13 |
|   1 |  20 |   3 | Text 3 | Set 20 |
|   1 |  14 |   4 | Text 4 | Set 14 |