简体   繁体   English

MySQL、PHP 和多表

[英]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.我试图从一个 mysql 表中获取一组值,然后在另一个表中搜索这些值并从中提取数据。 Imagine two tables: an orders table (id, product_id) and a products table (id, price).想象一下两个表:一个订单表(id,product_id)和一个产品表(id,price)。 I'm basically trying to use an array full of orders.id to sum products.price of those ids in the array.我基本上是在尝试使用一个充满 orders.id 的数组来对数组中这些 id 的 products.price 求和。

I've figured out how to get the array full of orders.id in PHP using我已经想出了如何在 PHP 中使用

    $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.所以问题是,现在我有了那个数组,我如何使用它来搜索另一个表中的任何 id,然后从该行中提取数据。

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'] .您可以使用$results_array获取产品 ID,然后执行另一个查询,就像您使用$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:正确的方法是执行 SQL 连接或简单的联合查询,如下所示:

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.当使用Where子句进行隐式连接时,它实际上是一个内部连接。 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.您可能需要查看此处(确保您阅读了有关连接的连续 5 页)以全面了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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