How To Left Join 2 Tables On 2 Different Databases?

后端 未结 4 2269
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 15:00

I have first database (dbA) with table like this, named Username :

+------------------+--------------+
| Username         |         


        
4条回答
  •  心在旅途
    2020-12-17 15:19

    You can simply join the table of different database. You need to specify the database name in your FROM clause. To make it shorter, add an ALIAS on it,

    SELECT  a.*,          -- this will display all columns of dba.`UserName`
          b.`Message`
    FROM  dba.`UserName` a  -- or LEFT JOIN to show all rows whether it exists or not
          INNER JOIN dbB.`PrivateMessage` b    
             ON a.`username` = b.`username`
    

    but some how, there are possiblities where-in a username won't have messages. In this case use LEFT JOIN if you want still to show all the records of dba.Username.

    Reading from your comments, the tables have different collation. The work around on this is to specify COLLATE on your joined statements,

    SELECT  a.*,          -- this will display all columns of dba.`UserName`
          b.`Message`
    FROM  dba.`UserName` COLLATE latin1_swedish_ci a  
          LEFT JOIN dbB.`PrivateMessage` COLLATE latin1_swedish_ci b    
             ON a.`username` = b.`username`
    

    you can change latin1_swedish_ci to whatever you want.

    For more info on COLLATION, see this full list of

    Character Sets and Collations in MySQL


    If you have enough privilege to ALTER the tables, simply use this syntax to manually convert and match their collations,

    ALTER TABLE tbl_name CONVERT TO CHARACTER SET latin2 COLLATE 'latin2_general_ci';
    

提交回复
热议问题