使用 php 从几个 mysql 表中检索数据的最佳方法

发布于 12-12 01:47 字数 678 浏览 0 评论 0原文

需要从几个表中获取数据 -表一包含所有产品详细信息和product_id -表二有额外的细节,与product_id相关

,从所有表获取数据的最佳方法是什么,也许将它们存储在同一个数组中,或者最好是单独的数组,但长度相同,

从表1获取数据

 $result = mysql_query("SELECT product_id,model,name,barcode FROM product");  
 $data = array();
 while($row = mysql_fetch_assoc($result))
 {
  $data[] = $row;
 }

如果我使用应该 我只是循环遍历 data[$i]['product_id'] 并再次查询并存储在新数组中? 例如

   $data2 = array();

   for($j=0; $j<=$count; $j++){
    $id = $data[$j]['product_id'];
    $result2 = mysql_query('SELECT stuff FROM product_descp WHERE product_id = $id');
    $row2 = mysql_fetch_array($result2);
    $data2[] = $row2['stuff'];
   }

Need to fetch data from a few tables
-table one has all product details and the product_id
-table two has extra details, associated with the product_id

what is the best way to get data from all tables and perhaps store them in the same array, or at best separate arrays but of same length

if i get the data from table 1 using

 $result = mysql_query("SELECT product_id,model,name,barcode FROM product");  
 $data = array();
 while($row = mysql_fetch_assoc($result))
 {
  $data[] = $row;
 }

should i just loop through data[$i]['product_id'] and query again and store in a new array?
e.g

   $data2 = array();

   for($j=0; $j<=$count; $j++){
    $id = $data[$j]['product_id'];
    $result2 = mysql_query('SELECT stuff FROM product_descp WHERE product_id = $id');
    $row2 = mysql_fetch_array($result2);
    $data2[] = $row2['stuff'];
   }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半岛未凉2024-12-19 01:47:35

最好的方法是让数据库处理一个大查询,而不是执行大量不同的查询(每个产品一个):

SELECT product_id,model,name,barcode 
FROM product 
JOIN product_descp 
ON product.product_id = product_descp.product_id

将其提取到数组中,就像您正在做的那样,就可以了。

The best way would be to let the database handle one big query, instead of performing lots of different queries (one per product):

SELECT product_id,model,name,barcode 
FROM product 
JOIN product_descp 
ON product.product_id = product_descp.product_id

Fetch that into an array as you are doing, and you are fine.

我做我的改变2024-12-19 01:47:35

由于这些表共享一个 product_id 字段,因此您可以在共享该 ID 的所有表之间执行 JOIN 查询,并将每个表中的所有列作为一个数组返回。
http://www.w3schools.com/sql/sql_join.asp

Since the tables share a product_id field you can do a JOIN query between all tables that share that ID and have all columns from each table returned as one array.
http://www.w3schools.com/sql/sql_join.asp

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文