2

In MySQL I have joined two tables which both have a column named 'Name'. In PHP I am writing a script that retrieve the values of the columns and store it in variables:

$row = mysql_fetch_array($result);

$table1name = $row['Name'];   
$table2Name = $row['Name'];

Of course the variables will not give the values of the 2 columns, but they will both give the same value from the column of the second table. Is there a way, without changing the name of the columns in the database, to retrieve the distinct values of both columns?

2
  • Note, although you should alias similar names, this has more do with PHP's mysql_fetch_array() than MySQL. Commented May 20, 2011 at 22:08
  • This is an SQL issue (which is solved by using aliases), not a PHP problem... Commented May 31, 2011 at 9:44

3 Answers 3

13

You need to use alias in mysql

SELECT table1.name AS name1
Sign up to request clarification or add additional context in comments.

Comments

8

yes. in your SQL query use the AS keyword to specify the desired alias.

Example:

SELECT `tbl_1`.`field` AS `tbl_1_field`, `tbl_2`.`field` AS `tbl_2_field` FROM....

back ticks are not required, that is just how I learned SQL

3 Comments

AS isn't required to define an alias, but it does make it more obvious
The keyword AS is also optional, at least in MySQL.
@yes123: it only gets worse, the higher your rep gets.
0

You can reference them in your mysql query with table qualifiers, eg tablea.id, and tableb.id, if you need both IDs in the results, you can do select tablea.id as id1, tableb.id as id2 etc.

2 Comments

Table aliasing will not solve the issue, only column aliasing will
I didnt say table aliases, I showed how to alias specific fields. I mentioned table qualifiers to reference them to then alias them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.