加入3个选择查询的结果

时间:2012-09-06 07:01:01

标签: sql database join

我想加入以下三个表,其中我的条件是t1.eid = 1.在连接表之后,我想用0填充空表格单元格。我认为首先将t1与t2连接,其中t1.eid = 1然后将结果与t3连接,其中两个表的结果为t3,其中t3.vid =新的result.vid。

数据样本:

CREATE TABLE t1 (
sid INT,
fid INT,
eid INT,
i INT,
uid INT);

INSERT INTO t1 (sid, fid, i, eid, uid) VALUES (1, 1, 1, 1, 1), (2, 2, 1, 1, 2), (3, 1,
1, 2, 1), (4, 2, 1, 2, 2), (5, 1, 1, 3, 1), (6, 2, 1, 3, 2), (7, 1, 1, 1, 3);


CREATE TABLE t2 (
d INT,
vid INT,
eid INT
);

INSERT INTO t2( d, vid, eid ) VALUES ( 1, 1, 1 ) , ( 1, 2, 1 ) , ( 1, 3, 2 ) , ( 1, 4, 
2 ) , ( 1, 5, 3 ) , ( 1, 6, 3 ) ;

CREATE TABLE t3 (
vid INT,
fr INT,
sr INT,
aj INT,
sj INT,
fid INT,
uid INT
);

INSERT INTO t3( vid, fr, sr, aj, sj, fid, uid ) VALUES ( 1, 0, 100, 0.1, 1, 1, 1 ) , ( 
2, 0, 1000, 1, 1, 2, 2 ) , ( 3, 0, 300, 0.1, 1, 1, 1 ) , ( 4, 0, 200, 1, 1, 2, 2 ) , ( 
5, 0, 1000, 0.25, 10, 1, 1 ) , ( 6, 0, 200, 1, 1, 2, 2 ) , ( 7, 0, 150, 1, 0.1, 1, 1 ) 
, ( 8, 0, 350, 1, 0.1, 1, 1 ) , ( 9, 0, 1050, 10, 0.25, 1, 1 ) , ( 10, 0, 1050, 1, 0, 
2, 2 ) , ( 11, 0, 250, 1, 0, 2, 2 ) , ( 12, 0, 250, 1, 0, 2, 2 ) ;

3 个答案:

答案 0 :(得分:1)

尝试这样的事情,

SELECT  a.*, b.*, c.*           -- select your desired columns here
FROM    t1 a INNER JOIN t2 b
            ON a.eid = b.eid
        INNER JOIN t3 c
            ON b.vid = c.vid
WHERE  a.eid = 2

OR

SELECT  b.d, a.fid, a.uid, a.i, a.eid, c.fr, c.sr, c.aj, c.sj
FROM    t1 a INNER JOIN t2 b
            ON a.eid = b.eid
        INNER JOIN t3 c
            ON b.vid = c.vid
WHERE  a.eid = 2

你可能想知道为什么tableName后面有字母。实际上他们被称为Alias。当你有更长的tableNames时,有时会很有帮助。

答案 1 :(得分:0)

SELECT t2.d, t1.fid, t1.uid, t1.i, t1.eid, 
    ISNULL(t3.fr), ISNULL(t3.sr), ISNULL(t3.aj), ISNULL(t3.sj)
FROM t1
INNER JOIN t2 ON t1.eid = t2.eid
RIGHT JOIN t3 ON t2.vid = t3.vid
WHERE  t1.eid = 1 OR t2.eid = 1

答案 2 :(得分:0)

select T2.D,t1.fid,t1.uid,t1.eid,t3.fr,t3.sr,t3.aj,t3.sj 
from T1 
    left outer join T2 ON t1.EID=t2.EID
    Left Outer JOin T3 ON T1.Fid=T3.Fid and T1.Uid=t3.Uid;