如果我理解正确,您只需要两个参考表和一个SELECT
with JOIN
。您CREATE TABLE
对三个表的语句可能如下所示
CREATE TABLE table1 (
data_column_1 int(10),
data_column_2 int(10),
data_column_3 int(10)
);
CREATE TABLE table2 (
data_column_2 int(10),
view_column_2 varchar(250)
);
CREATE TABLE table3 (
data_column_3 int,
view_column_3 varchar(250)
);
假设我们有以下样本数据
table 1
------------
10 1 3
20 2 2
30 3 1
table2
------------
1 Apple
2 Banana
3 Orange
table3
------------
1 Red
2 Green
3 Yellow
然后这SELECT
会给你想要的
SELECT t1.data_column_1,
t1.data_column_2,
t1.data_column_3,
t2.view_column_2,
t3.view_column_3
FROM table1 t1 LEFT JOIN
table2 t2 ON t1.data_column_2 = t2.data_column_2 LEFT JOIN
table3 t3 ON t1.data_column_3 = t3.data_column_3
我们LEFT JOIN
假设并非 data_column_2 和 data_column_3 中的所有值都分别在 table2.view_column_2 和 table3.view_column3 中有参考值。如果您总是在参考表中有相应的值,或者您想从结果集中过滤掉那些没有它们的值,那么请INNER JOIN
改用。
输出:
+---------------+---------------+---------------+---------------+---------------+
| data_column_1 | data_column_2 | data_column_3 | view_column_2 | view_column_3 |
+---------------+---------------+---------------+---------------+---------------+
| 10 | 1 | 3 | Apple | Yellow |
| 20 | 2 | 2 | Banana | Green |
| 30 | 3 | 1 | Orange | Red |
+---------------+---------------+---------------+---------------+---------------+
如果你愿意,你可以把它包在一个视图中
CREATE VIEW consolidated_table
AS
SELECT t1.data_column_1,
t1.data_column_2,
t1.data_column_3,
t2.view_column_2,
t3.view_column_3
FROM table1 t1 LEFT JOIN
table2 t2 ON t1.data_column_2 = t2.data_column_2 LEFT JOIN
table3 t3 ON t1.data_column_3 = t3.data_column_3
然后像这样使用它
SELECT *
FROM consolidated_table
WHERE data_column_1 < 20
输出:
+---------------+---------------+---------------+---------------+---------------+
| data_column_1 | data_column_2 | data_column_3 | view_column_2 | view_column_3 |
+---------------+---------------+---------------+---------------+---------------+
| 10 | 1 | 3 | Apple | Yellow |
+---------------+---------------+---------------+---------------+---------------+