1

是否可以在一个查询中从多个表中检索一组数据?例如,我从 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);

  ?>

谢谢

4

3 回答 3

0

您可以使用连接来执行此操作:

例如

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'

(未经测试)

可能值得一读。http://www.sitepoint.com/understanding-sql-joins-mysql-database/

于 2013-01-07T11:50:33.650 回答
0

如果你的表有一些共同点,比如 table1 的 1 列是 table2 的主键,或者任何类型的关系(比如同一列),你可以使用 JOINS。

否则你也可以使用 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'

但是两个 select 语句必须产生相同数量的列名称相同的列。

这对你有好处。

于 2013-01-07T12:06:27.867 回答
0

使用 Mysql 连接。

这是一个例子:

<?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 />";
}
?>

此处列出了更多 mysql 连接示例:http: //phpweby.com/tutorials/mysql/32

于 2013-01-07T13:30:47.397 回答