我有两个表,tbl_foo
和tbl_bar
,我想tbl_foo.foo_id = tbl_bar.foo_id
在 on-clause 中加入这些表。但是,对于每个都tbl_bar.baz_id
应该有一行tbl_foo.foo_id
(即使不tbl_bar
存在这样的条目)。我该如何编写这样的查询?
下面有关于架构和我想要的结果的更多信息。
- 编辑:每一行必须有一个
foo_id
andbaz_id
。 - 编辑2:在下面添加
tbl_baz
。
期望的结果
+--------+--------+--------+------------+
| bar_id | baz_id | foo_id | some_field |
+--------+--------+--------+------------+
| 1 | 101 | 1 | foo |
| 2 | 101 | 2 | bar |
| 3 | 101 | 3 | baz |
| NULL | 101 | 4 | bin |
| 4 | 102 | 1 | foo |
| NULL | 102 | 2 | bar |
| 5 | 102 | 3 | baz |
| NULL | 102 | 4 | bin |
+--------+--------+--------+------------+
表:tbl_foo
+--------+------------+
| foo_id | some_field |
+--------+------------+
| 1 | foo |
| 2 | bar |
| 3 | baz |
| 4 | bin |
+--------+------------+
表:tbl_bar
+--------+--------+--------+
| bar_id | baz_id | foo_id |
+--------+--------+--------+
| 1 | 101 | 1 |
| 2 | 101 | 2 |
| 3 | 101 | 3 |
| 4 | 102 | 1 |
| 5 | 102 | 3 |
+--------+--------+--------+
表:tbl_baz
+--------+
| baz_id |
+--------+
| 101 |
| 102 |
+--------+
SQL 架构
CREATE TABLE tbl_foo (
foo_id INT,
some_field VARCHAR(255),
PRIMARY KEY (foo_id)
);
INSERT INTO tbl_foo VALUES
(1, 'foo'),
(2, 'bar'),
(3, 'baz'),
(4, 'bin');
CREATE TABLE tbl_bar (
bar_id INT,
baz_id INT,
foo_id INT,
PRIMARY KEY (bar_id, baz_id),
FOREIGN KEY (baz_id) REFERENCES tbl_baz (baz_id),
FOREIGN KEY (foo_id) REFERENCES tbl_foo (foo_id)
);
INSERT INTO tbl_bar VALUES
(1, 101, 1),
(2, 101, 2),
(3, 101, 3),
(4, 102, 1),
(5, 102, 3);
CREATE TABLE tbl_baz (
baz_id INT,
PRIMARY KEY (baz_id)
);
INSERT INTO tbl_baz VALUES
(101),
(102);