I have two tables in my database:
NEWS ('id' - the news id, 'user' - the user id of the author)
USERS ('id' - the user id)
I want to make a SELECT * FROM news JOIN users ON news.user = user.id
, now when I get the results in PHP it's something like:
$row = mysql_fetch_array($result)
, and get column names by $row['column-name']
... how do I get the news ID and the user ID, having the same column name?
UPDATE: Thanks everybody for the quick answers. Aliases seem the best solution.
You can do something like
And then
$row['news_id']
will be the news id and$row['user_id']
will be the user idYou can either use the numerical indices (
$row[0]
) or better, useAS
in the MySQL:SELECT *, user.id AS user_id FROM ...
I just figured this out. It's probably a bad practice but it worked for me in this case.
I am one of the lazy people who doesn't want to alias or write out every column name with a table prefix.
You can select all of the columns from a specific table by using
table_name.*
in your select statement.When you have duplicated column names, mysql will overwrite from first to last. The data from the first duplicated column name will be overwritten when it encounters that column name again. So the duplicate column name that comes in last wins.
If I am joining 3 tables, each containing a duplicated column name, the order of the tables in the select statement will determine what data I am getting for the duplicate column.
Example:
In the example above, the value of
dup
I get will be fromtable3
.What if I want
dup
to be the value fromtable1
?Then I need to do this:
Now,
table1
comes last, so the value ofdup
will be the value from table1.I got the value I wanted for
dup
without having to write out every single freaking column and I still get all of the columns to work with. Yay!I know the value of
dup
should be the same in all 3 tables, but what iftable3
doesn't have a matching value fordup
? Thendup
would be blank in the first example, and that would be a bummer.