Viju
Viju

Reputation: 427

mysql get name by id in select query in multiple records

i've stuck in mysql query. i've a employee table whose fields are id, name, bossid and bossid is parent id of employee.

enter image description here

How i write the query to print the data in this format

 id   name     boss
 1    rajesh   rajesh
 2    vijay    rajesh
 3    ravi     vijay

Upvotes: 1

Views: 2820

Answers (2)

Jens
Jens

Reputation: 69440

Just join the table with itself:

Select t1.id as id 
     , t1.name as Name 
     , t2.name as boss 
  from employee t1 
  join employee t2 
    on t1.bossid = t2.id

Upvotes: 1

Kaja Mydeen
Kaja Mydeen

Reputation: 585

SELECT id, name, 
  (SELECT B.name from `users` B WHERE B.id = A.bossid) bossname 
  FROM `users` A

Try this http://sqlfiddle.com/#!9/ddb50/2

Upvotes: 2

Related Questions