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! :)

3
  • 4
    Possible duplicate of mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object Commented Oct 24, 2015 at 17:10
  • 1
    You can find the answer here... it is well explained. Commented Oct 24, 2015 at 17:13
  • Switch to the mysqli_* interface before your code breaks. Commented Nov 1, 2015 at 20:55

1 Answer 1

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.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.