2010-10-21 50 views
0

我有三個表,我想以一種方式生成一個表和所有匹配記錄中的所有記錄,或從另一個表中生成NULL。必須返回第一個表中的所有記錄。我以爲我曾經這樣做過,但我不記得何時何地,MySQL只是不玩球。MySQL聯接,聯結表中的空行

SELECT VERSION(); 
5.0.51a-3ubuntu5.7 

/* Some table that may or may not be needed, included to give context */ 
CREATE TABLE `t1` (
    `a` int(4) NOT NULL, 
    `a_name` varchar(10) NOT NULL, 
    PRIMARY KEY (`a`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

CREATE TABLE `t2` (/* "One table" */ 
    `b` int(2) NOT NULL, 
    `b_name` varchar(10) NOT NULL, 
    PRIMARY KEY (`b`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

CREATE TABLE `t3` (/* "Another table" */ 
    `a` int(4) NOT NULL, 
    `b` int(2) NOT NULL, 
    PRIMARY KEY (`a`,`b`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

INSERT INTO t1 VALUES (1, '1-one'),(2, '1-two'),(3, '1-three'); 
INSERT INTO t2 VALUES (1, '2-one'),(2, '2-two'),(3, '2-three'), 
         (4, '2-four'),(5, '2-five'); 
INSERT INTO t3 VALUES (1,1),(1,2),(1,3),(1,4),(2,2),(2,5); 

t3t1t2結合表。結果集我想找應該是這樣的任何a=n

n=1 
b | b_name | a 
------------------- 
1 | 2-one | 1 
2 | 2-two | 1 
3 | 2-three | 1 
4 | 2-four | 1 
5 | 2-five | NULL 

n=2 
b | b_name | a 
------------------- 
1 | 2-one | NULL 
2 | 2-two | 2 
3 | 2-three | NULL 
4 | 2-four | NULL 
5 | 2-five | 2  

n=7 
b | b_name | a 
------------------- 
1 | 2-one | NULL 
2 | 2-two | NULL 
3 | 2-three | NULL 
4 | 2-four | NULL 
5 | 2-five | NULL 

a在結果中實際設置的值並不重要,只要它明確地反映出記錄t3存在或不存在(那有意義嗎?)。

查詢

SELECT t2.b, t2.b_name, a 
    FROM t2 
    LEFT /* OUTER */ JOIN t3 ON t3.b = t2.b 
    WHERE (
    a = 2 
    OR 
    a IS NULL 
    ); 

回報

b | b_name | a 
------------------- 
2 | 2-two | 2 
5 | 2-five | 2  

可以這樣做?

回答

1
SELECT t2.b, t2.b_name, MAX(IF(a=2, a, NULL)) AS a 
FROM t2 
    LEFT OUTER JOIN t3 
      ON t3.b = t2.b 
GROUP by t2.b 
ORDER BY b ASC; 
0

像這樣的東西?如果沒有,你可以舉一個你想得到的輸出的例子。

 

select * from t1 
left join t3 using(a) 
left join t2 using(b) 
 
+0

有在原崗位示例輸出,第二碼塊。 – mkjeldsen 2010-10-21 10:58:35

+0

@奎瓦爾對不起,我的壞。 – jasper 2010-10-21 13:08:30