I need to SELECT from more than one table that has a lot of fields. Do I have to manually fabricate the query like this:
table1.field1 AS table1_field1, table1.field2 AS table1_field2, ..., table2.field1 AS table2_field1, ...
Or is there any workaround for this in MySQL or PHP that will automatically take care of all these when there are identical field names in the tables?
In PHP, I tried:
$results = $conn -> query("SELECT table1.*, table2.* FROM table1, table2 WHERE 1"); // $conn is a mysqli object
$results = $results -> fetch_array();
But if there is a field named ‘title’ in both of the 2 tables, $results[‘title’] would just contain the value of the record from the 2nd table.
I know there are numeric indexes that you can use to access the value but:
- It’s unreadable.
- You have to update the code accordingly every time the table structure such as the order of the fields changes.
Any idea?
Yes, there are workarounds.
mysql and mysqli extensions, as well as certain pdo drivers, have functions to let you get at column meta data. Heres a pdo sample
So you can use table1.* and be able to differentiate conflicting column names.
Also, another trick that works because the column order in the result set is deterministic.
I’ll leave the code up to you, but you can fetch a row as an array, and loop through the array keys. Since they will be in order, you can assume each column that follows a table separator column belongs to the table specified by the separator, until you come across the next sep.