MySql: How to read a table from one database while searching second database table per each row?
I am new to MySql/PHP.
Each row from Database1.table1 has to be read and display. It contains a column which has search term that I need to pass on to Database2.table2 and process the returns per each row read. Currently I am making new connection to Database2.table2 for each row in db1.table1 which is really slow and inefficient. I can not change the table structures.
Thanks!
tables
db1 table1:
id_row type model har status id date
1 ATX Hybrion 88-85-5d-id-ss y aaa12345 2011/08/12
2 BTX Savin none n aaa12345 2010/04/05
3 Full Hp 44-55-sd-qw-54 y 开发者_运维知识库 ashley a 2011/07/25
4 ATX Delin none _ smith bon 2011/04/05
db2 table2:
id_row id first_name last_name dept telephone
1 aaa12345 joe smith ANS 800 555 5555
2 bbb67890 sarah brown ITL 800 848 8848
So the database 1 table 1 is the one that gets read and displayed, db2 table2 is read and info displayed if ID is positive match. ID is only unique in the db2 table2, db1 table1 one has multi format column so it could or could not be an ID as well as those rows could have duplicate ID. Hope this gives better understanding of what i need. Thanks again!
Someone suggested to use EXISTS
but I don't know how, given the situation.
Assuming the user you're running as has the correct rights to see both databases, then you should be able to do this by joining the tables using the 'dbname.tablename' syntax like this:
select t1.*, t2.*
from database1.table1 t1
LEFT OUTER JOIN database2.table2 t2 ON t1.id = t2.id
this will give you all rows from table A, and where there is a matching row in table b, the matching rows from there as well (or nulls if there is no matching row)..
精彩评论