简体   繁体   中英

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?

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 ...
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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM