简体   繁体   English

PHP多个MySQL查询

[英]Php multiple mySQL query

is it possible to retrieve an array of data from more than one table within one query? 是否可以在一个查询中从多个表中检索数据数组? For example , I am getting an array from table1, but I want to retrieve data from several other tables too: 例如,我从table1获取一个数组,但是我也想从其他几个表中检索数据:

<?php


   $con = mysql_connect($hostname,$username, $password);
   if (!$con)
     {
     die('Could not connect: ' . mysql_error());
   }
   mysql_select_db($dbname, $con);

   $today = date('Y-m-d H:i:s', time());
   $today1DayAgo = date('Y-m-d H:i:s', strtotime("$today -1 day"));
   $query = "SELECT * FROM table1 WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'";

   $result = mysql_query($query);

   while($row = mysql_fetch_array($result)){
       echo $row["omtr_page_view"]);
   }

   mysql_close($con);

  ?>

Thanks 谢谢

You can use joins to do this: 您可以使用联接执行此操作:

Eg 例如

SELECT t1.*, t2.id, t2.someothercolumn FROM table1 t1 LEFT JOIN table2 t2 ON t1.id=t2.t1_id WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'

(Untested) (未经测试)

Might be worth reading up on them.. http://www.sitepoint.com/understanding-sql-joins-mysql-database/ 可能值得阅读。.http ://www.sitepoint.com/understanding-sql-joins-mysql-database/

If your tables have something in common, like 1 column of table1 is the primary key of table2, or any kind of a relation (like same column), you can use JOINS. 如果您的表有一些共同点,例如table1的1列是table2的主键,或任何类型的关系(例如同一列),则可以使用JOINS。

Otherwise you can use UNION as well, like 否则,您也可以使用UNION,例如

SELECT omtr_date1.a AS a1, omtr_date1.b AS b1 FROM table1 WHERE omtr_date1 BETWEEN '$today1DayAgo' AND '$today'
UNION
SELECT omtr_date2.c AS a1, omtr_date2.d AS b1 FROM table1 WHERE omtr_date2 BETWEEN '$today1DayAgo' AND '$today'

But both the select statements must produce same number of columns with same column names. 但是,两个select语句必须产生具有相同列名的相同数量的列。

That will do you good. 那对你有好处。

Use Mysql Joins. 使用Mysql连接。

Here is an example: 这是一个例子:

<?php
// Make a MySQL Connection

// Construct our join query
$query  = "SELECT family.Position, food.Meal ";
$query .= "FROM family INNER JOIN food ";
$query .= "WHERE family.Position = food.Position";

//Execute query  
$result = mysql_query($query) or die(mysql_error());

// Print out the contents of each row into a table 
while($row = mysql_fetch_array($result)){
    echo $row['Position']. " - ". $row['Meal'];
    echo "<br />";
}
?>

More examples of mysql joins are listed here: http://phpweby.com/tutorials/mysql/32 此处列出了mysql连接的更多示例: http : //phpweby.com/tutorials/mysql/32

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

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