How to select fields from different db with the same table and field name

I have two databases, because the so argument allows us to name them db1 and db2. they are both structured exactly the same, and both have a table called table1, both of which have id and value1 values.

My question is: how can I execute a query that selects the value of field1 for both tables linked by the same identifier ???

+3
source share
5 answers

You can prefix table names with the database name to identify two identically named tables. You can then use this fully qualified table name to denote identically named fields.

So, without aliases:

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

and with pseudonyms

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

, :

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

T-Sql, , mysql ( , )

SELECT
  a.Value1 AS [aValue]
  ,b.Value1 AS [bValue]
FROM
  db1.dbo.Table1 a
  INNER JOIN db2.dbo.Table1 b
    ON a.Id = b.Id
+1

- .

$dbhost="server_name";
$dbuser1="user1";

$dbpass1="password1";

$dbname1="database_I";
$dbname2="database_II";
$db1=mssql_connect($dbhost,$dbuser1,$dbpass1);

mssql_select_db($dbname1,$db1);

$query="SELECT ... FROM database_I.table1, database_II.table2 WHERE ....";

.. , .

0

sql . FROM, select... tablename

... .namespace.tablename

- dbo.

0

union:

:

select "one" union select "two";

This will return 2 lines, the first line contains one, and the second line contains two. As if you are combining 2 sql queries, the only constant is that both of them should return the same number of columns.

Multiple Databases:

select * from client_db.users where id=1 union select * from master_db.users where id=1;

In this case, both user databases must have the same number of columns. You said that they have the same structure, so you should not have problems.

0
source

Source: https://habr.com/ru/post/1764172/


All Articles