Che MAUVAIS COMPTE
Che MAUVAIS COMPTE

Reputation: 131

PDO select from multiple identical tables

I want to fetch datas from multiple identical tables (three and even more), they got the same columns names (but different datas in the rows).

So, I want to fetch with loops all the tables as if it was one query (one loop), not three.

I do not want to triple the number of columns when fetching the array. I want all the tables to use the same columns names. The datas of the tables will be stacked one over the other in the array, not one next to the other, tripling the number of columns in the array. But, once they get stacked one over the other, the "ORDER BY" filter will "blend" the tables : the "ORDER BY" will act on all the tables at once (like if it was only one table), not on all the tables individually.

My query for 1 table looks like this :

$pdo = "SELECT * FROM " .$table1 ." ORDER BY price LIMIT " 
       .$current_page_offset .", " .$items_per_pages;

So...I want to fetch the three tables like if I was fetching only one.

*also want to keep my limit and "ORDER BY" even more filters working. I do not want a triple-limit showing three times the number of items i want on my page...

Is there a way to do that ?

*EDIT : I changed my description of "blended" at 3rd paragraph. sorry for (maybe) my bad English.

Upvotes: 0

Views: 420

Answers (1)

eggyal
eggyal

Reputation: 125865

You want to use UNION:

UNION is used to combine the result from multiple SELECT statements into a single result set.

Therefore, if your table names are in an array called $tables:

mb_regex_encoding($charset); // character set of database connection
foreach ($tables as $table) {
  $table = '`'.mb_ereg_replace('`','``',$table).'`';
  $sql[] = "(
    SELECT   *
    FROM     $table
    ORDER BY price
    LIMIT    $current_page_offset, $items_per_pages
  )";
}
$sql = implode(' UNION ALL ', $sql);

However it sounds as though your schema should be normalised, such that you don't have such "identical" tables: instead have a single table with an additional column to indicate whatever distinguishes each.

Upvotes: 2

Related Questions