简体   繁体   English

具有相同列名但ID不同的2个表的视图

[英]view of 2 tables with same column name but ids are different

I have 2 tables in MySQL t1 and t2. 我在MySQL t1和t2中有2个表。 Both have same column names. 两者具有相同的列名。 Table t1 has huge data and t2 is not so huge as compared to t1 but in mean time t2 would also be of the same size as t1. 表t1拥有大量数据,而t2与t1相比并没有那么大,但同时t2的大小也与t1相同。 The only difference is that the id column do not match in both the tables. 唯一的区别是,两个表中的id列都不匹配。 I want to create a view out of these column. 我想从这些列中创建一个视图。

What I have created is 我创造的是

CREATE VIEW vw_t1t2 AS  SELECT id , name , lastname, depid FROM t1
Union
SELECT  id , name , lastname, depid FROM t2;

If I do a query "Select * from vw_t1t2 where depid='100287'". 如果执行查询“从vw_t1t2选择*,其中depid ='100287'”。

The view does not fetch the correct data, the data is mixture on all the records when I search for particular department id, some records are of different department id. 该视图未获取正确的数据,当我搜索特定的部门ID时,所有记录中的数据都是混合的,某些记录具有不同的部门ID。 Also it took 200 sec to execute the query. 同样花了200秒执行查询。

you may consider to wrap the result of the union 您可以考虑包装合并的结果

SELECT * FROM
(
   SELECT id , name , lastname, depid FROM t1
   Union
   SELECT  id , name , lastname, depid FROM t2
) as sel1
WHERE depid = 2

but let us see the EXPLAIN output to optimize the query 但是让我们看一下EXPLAIN输出来优化查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM