5

How can I select data in the same query from two different databases into the same server? This is what I'm doing, but my query doesn't works:

$sqlquery = "SELECT * FROM database_2.table_2 WHERE database_1.table_1.data_1 LIKE database_2.table_2.data_2";

$result = mysql_query($sqlquery);
$number = mysql_numrows($result);

$i = 0;
if ($number < 1) {
  print "DOH";

}else{
  while ($number > $i) {
    $content = mysql_result($result,$i,"database_2.table_2.data_3");
    print "$content";
    $i++;
  }
}
5
  • 1
    define " doesn't work"? errors? you don't actully check if your SELECT query works or produces an error Commented Aug 27, 2013 at 23:11
  • Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in /web/htdocs/...etc on line 88 [$number = mysql_numrows($result);] Commented Aug 27, 2013 at 23:18
  • 1
    that means the querry failed Commented Aug 27, 2013 at 23:18
  • 1
    why the like condition? can't you simply use = (it's cheaper) Commented Aug 27, 2013 at 23:23
  • And running the same query in any MySQL shell (or phpMyAdmin) would work? Commented Sep 28, 2023 at 13:49

2 Answers 2

5

The problem is not about different databases.

Your WHERE clause references the field database_1.table_1.data_1 which was not supplied in the FROM clause.

Didn't you mean something like

SELECT * 
FROM database_2.table_2 
JOIN database_1.table_1 
     ON (database_2.table_2.some_field = database_1.table_1.some_other_field) 
WHERE database_1.table_1.data_1 LIKE database_2.table_2.data_2

?

Also,

echo mysql_error();

after your failed query - this will give you a clue about what's wrong.

Sign up to request clarification or add additional context in comments.

2 Comments

Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='
SELECT * FROM database_2.table_2 JOIN database_1.table_1 ON (database_2.table_2.some_field = database_1.table_1.some_other_field) WHERE database_1.table_1.data_1 LIKE database_2.table_2.data_2 COLLATE utf8_general_ci
0

try this

    SELECT * FROM database_2.table_2 t2 INNER JOIN database_1.table_1 t1 
    ON  t1.data_1 = t2.data_2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.