如何从具有相同表和字段名称的不同数据库中选择字段

问题描述:

我有两个数据库,出于参数的缘故,让我们将它们称为db1和db2.它们的结构完全相同,并且都有一个名为table1的表,它们都有字段id和value1.

I have two databases, for argument sake lets call them db1 and db2. they are both structured exactly the same and both have a table called table1 which both have fields id and value1.

我的问题是我该如何执行查询,以为由相同ID链接的两个表选择字段value1?

My question is how do I do a query that selects the field value1 for both tables linked by the same id???

您可以在表名前添加数据库名称,以标识两个名称相似的表.然后,您可以使用该标准表名来引用类似命名的字段.

You can prefix the table names with the database name to identify the two similarly named tables. You can then use that fully qualified table name to refer to the similarly named fields.

因此,没有别名:

select db1.table1.id, db1.table1.value1, db2.table1.value1
from db1.table1 inner join db2.table1 on db1.table1.id = db2.table1.id

并带有别名

select t1.id, t1.value1, t2.value1
from db1.table1 as t1 inner join db2.table1 as t2 on t1.id = t2.id

您可能还想为选定的列加上别名,以便您的选择行变为:

You may also want to alias the selected columns so your select line becomes:

select t1.id as id, t1.value1 as value_from_db1, t2.value1 as value_from_db2