0

I've work with many records and I don't know what is better solution (I mean the fastest):

    $result = mysql_query("SELECT `user_id` FROM `table_1` WHERE `user_id` = '$id'");
    while($row = mysql_fetch_array($result)) {
            $var = mysql_fetch_object(mysql_query("SELECT `row` FROM `table_2` WHERE `id` = '{$row['user_id']}'"));
            echo $var->row;
    }

or

    $result = mysql_query("SELECT t1.`user_id`, t2.`row` FROM `table_1` t1 INNER JOIN `table_2` t2 ON (t2.`id` = t1.`user_id`)");
    while($row = mysql_fetch_array($result)) {
           echo $row['row']; 
    }

Thank you for your advices! :)

  • 4
    Possible duplicate of [mysql\_fetch\_array, mysql\_fetch\_assoc, mysql\_fetch\_object](http://stackoverflow.com/questions/1536813/mysql-fetch-array-mysql-fetch-assoc-mysql-fetch-object) – Luis Teijon Oct 24 '15 at 17:10
  • 1
    You can find the answer [here](http://stackoverflow.com/questions/1536813/mysql-fetch-array-mysql-fetch-assoc-mysql-fetch-object)... it is well explained. – Lorena Pita Oct 24 '15 at 17:13
  • Switch to the mysqli_* interface before your code breaks. – Rick James Nov 01 '15 at 20:55

1 Answers1

1

Whatever is handled at the database is generally faster than whatever is handled at the scripting side. So i would recommend that always go with the joins. your second part of code where you have used the SQL JOIN is better.

e.g. you can easily see that in the first code there is one extra call being made to the database which is not the case in the second code. So for every entry that is fetched in the first loop you will have to again look into the database. e.g. your first loop returns 100 records then in the second loop it will look in the database again for 100 times. so it makes it slow.

MansoorShiraz
  • 118
  • 1
  • 8