如何从表A和B得到所有结果? (外连接不存在?)

时间:2011-08-09 22:16:59

标签: mysql sql

最简单的解释方法是举例:

mysql> select * from table_a left join table_b on col_a=col_b;
+-------+-------+
| col_a | col_b |
+-------+-------+
|     1 |  NULL |
|     2 |  NULL |
|     3 |     3 |
|     4 |     4 |
+-------+-------+

mysql> select * from table_a right join table_b on col_a=col_b;
+-------+-------+
| col_a | col_b |
+-------+-------+
|     3 |     3 |
|     4 |     4 |
|  NULL |     5 |
|  NULL |     6 |
+-------+-------+

但我怎么得到这个?

mysql> select * from table_a ???? table_b on col_a=col_b;
+-------+-------+
| col_a | col_b |
+-------+-------+
|     1 |  NULL |
|     2 |  NULL |
|     3 |     3 |
|     4 |     4 |
|  NULL |     5 |
|  NULL |     6 |
+-------+-------+

@Abe的结构:

CREATE TABLE IF NOT EXISTS `table_a` (
  `col_a` int(11) NOT NULL,
  PRIMARY KEY (`col_a`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


INSERT INTO `table_a` (`col_a`) VALUES
(1),
(2),
(3),
(4);

CREATE TABLE IF NOT EXISTS `table_b` (
  `col_b` int(11) NOT NULL,
  PRIMARY KEY (`col_b`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


INSERT INTO `table_b` (`col_b`) VALUES
(3),
(4),
(5),
(6);

2 个答案:

答案 0 :(得分:5)

由于MySQL中没有FULL OUTER JOIN选项,我认为您只能使用UNION

select * from table_a left join table_b on col_a=col_b
UNION 
select * from table_a right join table_b on col_a=col_b

答案 1 :(得分:3)

本文提供了几种使用MySQL模拟完全外连接的方法。

http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

希望这会有所帮助。