Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner join vs foreach loop performance

I'm trying to do something and I'm sure if I'm doing it in a right way. Let's say I have two tables in MySQL database with the following columns

-------------------------

Members
-------------------------
id        name      status
-----     -----     -----
1         Mike      0
2         Alex      0
3         John      1
4         Jack     -1

-------------------------

    Status
    -------------------------
    id        text
    -----     -----
   -1        disapproved
    0         reviewing
    1         approved

Now I need to display the information of the table "Members" in the following way:

id        name      status
-----     -----     -----
1         Mike      reviewing
2         Alex      reviewing
3         John      approved
4         Jack      disapproved

One way is to use an Inner Join between the two tables and the other way is to extract data from the "Members" table and put it inside a for-each loop and convert status values. In the latter way I don't need the "status" table at all.

I'm not sure which way is better. please let me know if you need more information to help me.

Thanks in advance.

Update

An for-each example for what I want to do is like this, supposing I have extracted data from "Memberes" table

foreach($data as $value)
    {
    if ($value['status'] == 0)
        $value['status'] = 'reviewing';
    if ($value['status'] == 1)
        $value['status'] = 'approved';      
    else
        $value['status'] = 'diapproved';        
    }
like image 742
user3530012 Avatar asked Apr 17 '26 19:04

user3530012


1 Answers

In general, you absolutely want to be doing this via a join inside your MySQL database:

SELECT
    t1.id, t1.name, t2.text AS status
FROM Members t1
INNER JOIN Status t2
    ON t1.status = t2.id

The alternative of handling this inside your PHP code with a foreach loop is unattractive for several reasons. First, you would probably need to bring in all information from both tables, which is wasteful from both a memory and network usage point of view. Then, even after you have brought in the data, you would be relying on PHP to perform the join. PHP wasn't really designed for in house database operations, and cannot use something like an index to speed up the process.

like image 65
Tim Biegeleisen Avatar answered Apr 19 '26 07:04

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!