简体   繁体   English

使用来自2个数据库的表进行查询

[英]Query with a table from 2 databases

I have 3 tables, t1,t2, and t3. 我有3个表,t1,t2和t3。 ti and t2 are in databases D1 . ti和t2在数据库D1中。 But table t3 is contained in both databases D1 AND D2 like some 5 records are in D1,t3 and rest 5 in D2.t3. 但是表t3包含在两个数据库D1和D2中,就像D1,t3中有大约5条记录,D2.t3中是其余5条记录一样。

the full table t3 is actually combined of records of the same table (ie, t3) from D1 AND D2 完整表t3实际上是来自D1和D2的同一表(即t3)的记录的组合

the query should be like; 查询应该像;

select t1.*,t2.* from D1.t1,D1.t2 where t1.aid=t3.cid and t3.id IN(1,2,4) and  t1.aid=t2.bid

the problem is how can i provide 't3.cid and t3.id IN(1,2,4)' IN THE QUERY since they are from different databases 问题是我如何在查询中提供“ t3.cid和t3.id IN(1,2,4)”,因为它们来自不同的数据库

MySQL databases are mostly for organization and permission sharding. MySQL数据库主要用于组织和权限分片。 There is very little overhead joining tables from multiple databases into a single query. 将来自多个数据库的表联接到单个查询中的开销很小。

SELECT *
    FROM D1.t1 as d1t1
    INNER JOIN D1.t2 as d1t2 ON d1t1.aid = d1t2.bid
    INNER JOIN D2.t3 as d2t3 ON <your join condition here>
    INNER JOIN D1.t3 as d1t3 ON <another join condition>
WHERE
    d1t3.id IN (1,2,3)

You didn't specify the join condition in the original question but this query should get you started. 您没有在原始问题中指定连接条件,但是此查询可以帮助您入门。


After reading the comments, what you need is a UNION: 阅读评论后,您需要的是UNION:

(SELECT t3.* FROM D1.t3) UNION (SELCT t3.* FROM D2.t3)

You will need to repeat the join conditions above in each UNION clause. 您将需要在每个UNION子句中重复上述连接条件。

You should probably look at your database structure, though. 但是,您可能应该查看数据库结构。 The UNION will give you the data you need, but at the expense of performance. UNION将为您提供所需的数据,但是会降低性能。 If you have two tables with identical structures, you should see if there is a way to migrate your data into a single table. 如果您有两个具有相同结构的表,则应查看是否存在将数据迁移到单个表中的方法。

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

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