简体   繁体   中英

MySQL, PHP, and Multiple Tables

I am trying to get an array of values from one mysql table then search through another table for those values and pull data from them. Imagine two tables: an orders table (id, product_id) and a products table (id, price). I'm basically trying to use an array full of orders.id to sum products.price of those ids in the array.

I've figured out how to get the array full of orders.id in PHP using

    $results = mysql_query("SELECT id FROM orders WHERE some_value =" . $passed_value . "");
    while ($row = mysql_fetch_row($results))
      {
        $results_array[] = $row[0]; 
      }

So the question is, now that I have that array, how do I use it to search another table for any id in the array and then pull data from that row.

You can use the $results_array to get the product ID, and then do another query like the one you did using $results_array['product_id'] .

However, this is very inefficient. The proper way is to do an SQL join or a simple joint query like this:

SELECT orders.id, orders.product_id, products.price 
FROM orders, products 
WHERE orders.id = '" . $your_order_id . "' and products.id = orders.product_id

The resultant rows will have all the information you need from both tables.

UPDATE: More information

When using the Where clause to join implicitly, it is effectively an Inner Join. Ie it returns rows when there is at least one match in both tables. A left join on the other hand returns all rows from the first table, even if there are no matching rows in the second table (in which case you get the respective fields corresponding to the second table null).

So rather than performance (which is more determined by the indexes you have on your fields, although the type of join might have some impact), what you choose depends on what results you want to get. You might want to look here (make sure you read the 5 consecutive pages about joins) to get a full understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM