简体   繁体   English

MySQL INNER JOIN具有不同的列名

[英]MySQL INNER JOIN with different column names

Okay, so I have two tables, a news table and a users table. 好的,我有两个表,一个news表和一个users表。 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'] . 我只能使用$query['id']访问用户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. 因此,尽管我希望他们将其映射到table1的列名,但该联接似乎正在使用table2的列名。 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. 因此,即使该列在users表中被称为id ,我也想在user_id下访问它,因为我在JOIN查询中指定了该列。

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. 我之所以需要这样做,是因为如果我需要table1中的id ,它们都将被映射到名为id的列,而我只能获取users表的id

So is there any way to do this? 那么有什么办法可以做到这一点? Access the column from table2 under the name of the column in table1? 在table1中的列名下访问table2中的列?

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. 在MySQL中,您在select语句中指定的是在结果集中所调用的内容,因此您需要告诉它要给您什么。 you do that with the AS command 你用AS命令来做

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

That way you can call it whatever you want 这样你就可以随便叫

or grab the user_id from news with 或从新闻中获取user_id

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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