-4

我想加入以下三个表,我的条件是 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 ) ;
4

3 回答 3

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

或者

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。当您有更长的表名时,有时会有所帮助。

于 2012-09-06T07:05:46.453 回答
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
于 2012-09-06T07:07:43.407 回答
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;
于 2012-09-06T07:09:00.863 回答