简体   繁体   English

通过PHP查询从mysql表打印值的最佳方法

[英]Best way to print values from mysql table by querying through PHP

Most of the times in my pages, I need to print the value of only one field in the table, by using a loop. 在我的页面中,大多数时候,我需要使用循环来打印表中仅一个字段的值。 For example: 例如:

 <?php

 for($i=1;$i<=mysql_num_rows($result);$i++)
 {
     echo $row['name'];
     $sql1="select industry from table_industry where profid='".$row['prof']."'";
     $result1=mysql_query($sql1);
     $row1=mysql_fetch_array($result1);
     echo $row1['industry']; ?>
 }
 ?>

For example, I have 5000+ record in table and the above loop will execute 5000+ times. 例如,我在表中有5000多个记录,上面的循环将执行5000多次。

What would be the best way to print the value of the industry field from the table table_industry ? table_industry表中打印industry字段值的最佳方法是什么?

Is it the code I wrote above, or is there a method for faster execution? 是上面我写的代码,还是有一种更快执行的方法?

  1. Avoid looping over all 5000 records. 避免循环访问所有5000条记录。 Use a filtering or pagination 使用过滤或分页
  2. Even more avoid nested queries. 还要避免嵌套查询。 Use power of JOIN . 使用JOIN力量。

My best guess is that JOIN will help you out here. 我最好的猜测是, JOIN将在这里为您提供帮助。

With join you can instruct he MySQL server to combine different tables and access them in a single query, for example: 通过join您可以指示MySQL服务器组合不同的表并在单个查询中访问它们,例如:

SELECT
  table_prof.profid
, table_prof.name
, table_industry.industry 
FROM table_prof
JOIN table_industry USING ( profid )
ORDER BY table_prof.name ASC;

Generally speaking, querying the database in a loop is a very bad idea and should be avoided unless you know exactly why you are doing it. 一般来说,循环查询数据库是一个非常糟糕的主意,除非您确切知道为什么要这样做,否则应避免查询。 Querying in a loop can easily bring a database server to it's knees. 循环查询可以轻松地使数据库服务器屈服。

use JOIN 使用JOIN

if you want to include only those rows with values in industry table then sql will be 如果您只想在行业表中包含具有值的行,则sql将是

    SELECT 
     table_prof.profid 
    , table_prof.name 
    , table_industry.industry  
      FROM table_prof 
      JOIN table_industry USING ( profid ) 
      ORDER BY table_prof.name ASC;

and if you want to include all values from table table_prof then sql will be 如果要包括表table_prof中的所有值,则sql将是

      SELECT 
     table_prof.profid 
    , table_prof.name 
    , table_industry.industry  
      FROM table_prof 
      LEFT JOIN table_industry USING ( profid ) 
      ORDER BY table_prof.name ASC;

i think this will help you... 我认为这将帮助您...

为了遵循您的逻辑,我将选择所有信息,将其加载到哈希中并在哈希中进行迭代,而不是杀死数据库。

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

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