2

我有以下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 行,但其他 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
4

3 回答 3

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
于 2013-01-18T09:07:47.790 回答
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
于 2013-01-18T09:12:43.643 回答
0

你可以试试这个:

SQLFIDDLE 演示

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

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 |
于 2013-01-18T09:15:01.090 回答