Qub1
Qub1

Reputation: 1244

MySQL INNER JOIN with different column names

Okay, so I have two tables, a news table and a users table. They are set up as below:

news:

id title user_id contents

users:

id username password

When I run this query:

SELECT news.title, users.username, news.contents FROM news INNER JOIN users ON news.user_id=users.id  WHERE news.id=:id

I can only access the user id using $query['id']. So it appears that the join is using the column names from table2, although I want them to map it to the column names of table1. So even though the column is called id in the users table, I want to access it under user_id, since I specified that in the JOIN query.

I need this because if I ever need the id from table1, they would both be mapped to the column called id and I would only be able to get the id of the users table.

So is there any way to do this? Access the column from table2 under the name of the column in table1?

Upvotes: 1

Views: 3653

Answers (2)

Jared Wadsworth
Jared Wadsworth

Reputation: 847

In MySQL what you specify in the select statement is what it is called in the result set, so you need to tell it what to give you. you do that with the AS command

SELECT users.id AS user_id ... FROM ...

That way you can call it whatever you want

or grab the user_id from news with

SELECT news.user_id ... FROM ...

Upvotes: 1

gr3g
gr3g

Reputation: 2914

SELECT users.id AS id1, news.id AS id2, news.title, users.username, news.contents 
FROM news INNER JOIN users ON news.user_id=users.id  WHERE news.id=:id

echo $query['id1'] . $query['id2'];

Upvotes: 0

Related Questions