tags:

views:

104

answers:

2

Hi,

Which is the best aproach to select * from various tables but with same row name, cause normally i use $row['name'] but i have seven tables with the some name... how can i do this?

tkz Roberto

A: 

You'll need to explicitly specify column names instead of doing SELECT *. Here's how you'd use aliases to return results from two tables that have some conflicting names:

SELECT students.id AS student_id, students.name AS student_name, teachers.id AS teacher_id, teachers.name AS teacher_name FROM students, teachers

In general it's bad practice to use wildcards in SELECT statements. Sure, you can save yourself a few minutes when you're first writing some code, but you may be shooting yourself in the foot if/when you change the database schema in the future. You're also probably returning more data than you really need.

If you have several tables with the same field names and you'd like to automate the query, here's one possibility:

$tables = array('table1', 'table2', 'table3', 'table4');
$fields = array('field1', 'field2', 'field3', 'field4');
$select = '';
$from = '';
foreach ($tables as $table) {
  if ($from) $from .= ', ';
  $from .= $table;
  foreach ($fields as $field) {
    if ($select) $select .= ', ';
    $select .= "$table.$field as {$table}_{$field}";
  }
}
$sql = "SELECT $select FROM $from WHERE ...";
pix0r
Yeah, but for example, i have seven tables, one of each day week, and all have in1, out1, in2, out2 rows,i need to get all in1 and out1 of the seven tables, this i can do, my question is, in PHP how can i handle with this... cause all the rows have the same name!best options is select sunday.in1 as sundayin1 from ...???
Roberto
I added some PHP code you could use to automate this, if you have seven nearly identical tables.
pix0r
A: 

You can use query

SELECT t1.name AS t1_name, t2.name AS t2_name
FROM table1 t1
INNER JOIN table t2 ON ....

And then

$row['t1_name']
$row['t2_name']
Lukasz Lysik
this is what i need... tkz...
Roberto