Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

sql - PHP Mysql joins across databases

Lets say I have two separate databases, X and Y, on the same physical server.

All of my queries currently run out of X.

I find I have one table in Y I would like to be available to X for JOINS.

So... now I keep a copy of the one table I need for both X and Y in both X and Y, but the data in Y is constantly changing, so the copy soon becomes out of date. Not critical for this application, but for another I'm designing now this just won't do.

X right now only needs read access to the table in Y.

Is there an efficient way to do joins across the two databases?

I'd prefer a mysql solution as opposed to opening multiple database connections in php.

Thank you.

EDIT: So what becomes of these lines?:

$conn = mysql_connect('localhost','username','password');
@mysql_select_db('database_name',$conn)

And yes.. this is an old app, hence the mysql instead of mysqli. Suppose I could convert it.

EDIT2: So where I don't specify database_name.table_name and just specify table_name I get whatever is selected, and where I do specify database.table_name I get what I asked for.. right? Yep. Works.

EDIT3: Is there any significant performance hit by doing cross database joins versus joins within the same database? Nope. Looks just as fast.

Thank you all for your responses.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you have to alias the table in the other database:

select a.id
     , b.foreign_id
  from database1.table1 a
  join database2.table1 b
    on b.foreign_id = a.id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...