Mysqli join tables from 2 different databases

前端 未结 3 1847
无人及你
无人及你 2020-12-06 22:30

How Can I use this 2 connections to run a query which joins 2 tables? yesno.table1 and sushi.table1 ? lets say we join by id they both have the same id. how can

3条回答
  •  一向
    一向 (楼主)
    2020-12-06 23:20

    This is possible but not in the way you're attempting it.

    First, you will need to have a mysql user with permissions to access both databases.

    Then you simply reference the secondary database as part of the query.

    E.g.

    // Connect to Database -- dbuser has permissions for database1 and database2
    $this->db = new mysqli("localhost", "dbuser", "***", "database1");
    
    $query = "SELECT t1.*, t2.* 
                  FROM table_one AS t1
                  INNER JOIN database2.table_two as t2 ON ( t1.id = t2.remote_id ) ";
    

    This isn't possible if the databases are on two different servers.

提交回复
热议问题