任何人都可以帮助我如何创建连接两个具有相同列且没有重复的表的 View 吗?
例子:
我有两个表 T1 和 T2
T1
Id Name Date
-----------------------
1 AAA 2019-04-05
2 BBB 2019-04-06
3 CCC 2019-04-07
T2
Id Name Date
----------------------
4 DDD 2019-04-01
1 ABC 2019-03-01
2 DEF 2019-03-02
我的输出 View 应该是这样的
Id Name Date
------------------------
1 AAA 2019-04-05 (From T1)
2 BBB 2019-04-06 (From T1)
3 CCC 2019-04-07 (From T1)
4 DDD 2019-04-01 (From T2)
下面是我正在尝试的查询
CREATE VIEW view AS (
(
SELECT
t1.id,
t1.name,
t1.date,
FROM
T1 as t1
UNION
SELECT
t2.id,
t2.name,
t2.date,
FROM
T2 as t2
)
但是我得到了重复的记录。
最佳答案
您似乎想要一个优先级查询,table1
优先于 table2
。在 MySQL 中:
select t1.id, t1.name, t1.date
from table1 t1
union all
select t2.id, t2.name, t2.date
from table2 t2
where not exists (select 1 from table1 t1 where t2.id = t1.id);
这会从 table1
中选择所有行,然后从 table2
中选择在 table1 中没有匹配的
。id
的所有行
这假设 id
足以确定哪些记录是“重复的”。
关于mysql - 创建 View 连接两个具有相同列且没有重复的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56586932/