Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: select the same column multiple times from a table

Tags:

sql

I have a table called t_employee with columns ID, NAME

Another table called t_ticket with columns ID, DESCRIPTION, CREATED_BY, UPDATED_BY

Note that CREATED_BY and UPDATED_BY are employee IDs

How can I select such that I get results that go something like:

ID, DESCRIPTION, CREATED_BY, CREATED_BY_NAME, UPDATED_BY, UPDATED_BY_NAME

where CREATED_BY_NAME and UPDATED_BY_NAME are referred from the employee table.

I have done this using a temp table and doing updates, but it seems expensive.

Also the tables are fixed so I have no way of changing them.

Look forward to any suggestions.

like image 873
user2739963 Avatar asked Jun 30 '26 08:06

user2739963


1 Answers

Just join the same table multiple times giving it an alias (a different one for each join):

select
  t_ticket.ID, 
  t_ticket.DESCRIPTION, 
  t_ticket.CREATED_BY, 
  e1.name as CREATED_BY_NAME, 
  t_ticket.UPDATED_BY, 
  e2.name as UPDATED_BY_NAME
from
  t_ticket 
left join
  t_employee as e1 on e1.id = t_ticket.CREATED_BY
left join
  t_employee as e2 on e2.id = t_ticket.UPDATED_BY
like image 135
georstef Avatar answered Jul 02 '26 20:07

georstef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!