简体   繁体   中英

How to change column name while joining the query in mysql

I need to change the column name while joining the MySQL query. I am explaining my code below.

select * from grc_action left join grc_users on grc_action.action_owner=grc_users.user_id  

I am giving my table below.

grc_action:

id    name    action_owner

grc_users:

user_id   name

The above is my table structure and as both has same column name ie-name here I need to change the grc_users table column ie-name while fetching the record. Please help me to solve this problem.

You can use AS

SELECT table1.name AS exampleName, table2.name AS otherName FROM sometable

You can also use this on tables:

SELECT vltn.id, vltn.name FROM veryLongTableName AS vltn

You dont need to type the AS , you can just do SELECT table1.name exampleName to shorten it, but it increases readbility and maintanability to write it, so I recommend doing it with AS .

You may assign different aliases to the name columns from the two different tables.

select
    ga.id,
    ga.name as action_name,
    ga.action_owner,
    gu.user_id,
    gu.name as user_name
from grc_action ga
left join grc_users gu
    on ga.action_owner = gu.user_id;

Note that I also used table aliases which make the query easier to read. In general, doing SELECT * is undesirable, and it is usually better to explicitly list the columns you want.

select * 
from grc_action 
left join grc_users on grc_action.action_owner=grc_users.user_id 

changed query use this query

select *,grc_users.name as grcuser_name,grc_action.name as grcaction_name 
from grc_action 
left join grc_users on grc_action.action_owner=grc_users.user_id 

Here geting two name like this grcuser_name , grcaction_name

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