سؤال

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:

<?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

هل كانت مفيدة؟

المحلول

Use Mysql Joins.

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

نصائح أخرى

You can use joins to do this:

E.g.

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/

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.

Otherwise you can use UNION as well, like

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.

That will do you good.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top