Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer two database tables in same query in php/mysql

I have two different databases and I have to run a query where I am going to join tables from both databases in a single query. My query goes like this:

SELECT mm.* FROM tbl1 mm INNER JOIN tbl2 t ON mm.module_id=t.module_id WHERE mm.module_name NOT IN(SELECT module_name FROM tbl3)"

Here tbl1 and tbl2 are in one database and tbl3 is in the second database. Is it possible to run this query without HARD CODING the database names before the table names? I created common files global_config1.php and global_config2.php which have the database constants and other php database connection constants and am using require_once(global_config1.php) and require_once(global_config2.php) but the query fails.

like image 557
Aditya Avatar asked Dec 04 '25 01:12

Aditya


1 Answers

Try this:

SELECT Database1.TableA.ColumnA1, Database1.TableA.ColumnA2,
Database2.TableB.ColumnB1, Database2.TableB.ColumnB2
FROM Database1.TableA
INNER JOIN
Database2.TableB ON
Database1.TableA.ColumnA3 = Database2.TableB.ColumnB3

Now, you will see the complete result in a single row. In case, the column names are same in both databases, you will see the column names same in the result and it will be impossible to get the value in PHP because 2 or more column name is same. To accomplish this, lets write another query

like image 74
Vivek Pandey Avatar answered Dec 05 '25 13:12

Vivek Pandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!