MySQL连接,连接表中的空行

时间:2010-10-21 10:25:17

标签: mysql join

我有三个表,我希望以一种方式加入,从一个表和任何匹配的记录生成所有记录,或者从另一个表生成NULL。必须返回第一个表中的所有记录。我以为我以前做过这个,但我不记得何时何地,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    

可以这样做吗?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

这样的东西?如果没有,你能给出一个你想要得到的输出的例子。


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