I have 3 entities and each has a corresponding table. I have a task to search in these 3 tables so results will be shown at one page, mixing together according to sort conditions. I am looking for a proper solution. I have some ideas.
It's possible to perform 3 search queries for each table and then show the results in consideration of sort conditions. It is simple when I have the search results all on one page. When I need to split results to pages, I can use the following algorithm: I run the same 3 search queries and I save result rows IDs and table names in session for current search in the necessary sort order. I perform these queries only once at search start. According to the selected page I will find IDs in session and perform 3 simple queries to find rows by their IDs.
Do you have any ideas how to solve this problem better? I do it on the MySQL+PHP+Zend framework base.
Here's a basic way of doing this. For this example, each table has an 'id' and a 'timestamp' field, and we want to sort the results by the timestamp field.
<?
function bubblesort(array $items) {
// Sorts the items in a two-dimensional array based on a
// timestamp in the first field of the arrays passed.
do{
$flag = false;
for ($i = 0; $i < (count($items) - 1); $i++) {
if(strtotime($items[$i][0]) > strtotime($items[$i + 1][0])) {
$swap = $items[$i];
$items[$i] = $items[$i + 1];
$items[$i + 1] = $swap;
$flag = true;
}
}
}
while($flag);
return $items;
}
$results = array();
// Get results for the first table
$result = mysql_query("SELECT `timestamp`, `id` FROM `table1`;");
if (!$result)
die(mysql_error());
while ($row = mysql_fetch_array($result))
$results[] = array($row[0], $row[1]);
// Get results for the second table
$result = mysql_query("SELECT `timestamp`, `id` FROM `table2`;");
if (!$result)
die(mysql_error());
while ($row = mysql_fetch_array($result))
$results[] = array($row[0], $row[1]);
// Get results for the third table
$result = mysql_query("SELECT `timestamp`, `id` FROM `table3`;");
if (!$result)
die(mysql_error());
while ($row = mysql_fetch_array($result))
$results[] = array($row[0], $row[1]);
// Sort the joint results
$results = bubblesort($results);
?>
Of course, each of the queries will have to be adapted for the individual table. Note that I've used a bubble sort alogrithm, depending on the amount of results you're expecting, a different sorting algorithm might be better.
It may also be better to merge the three SELECT queries into one by using UNION (see the documentation), but I don't know enough about the structure of the tables to tell you the query you'd need.