简体   繁体   中英

join with two columns and get field values from their foreign key with single sql query

I have two tables:

  1. tbl_users (id,first_name,last_name,email,password)
  2. tbl_claims (id, claimed_by, claimed_to) (both claimed_by and claimed_to is user_id of tbl_users table means foreign key)

Now how can i get the first_name and last_name of both claimed_by and claimed_to userid with single sql query?

I am trying below query but i gives unknown column error while i am using it in where clause.

SELECT c.*,
(select first_name from tbl_users where id=c.claimed_by) as claimed_by_fname,
(select last_name from tbl_users where id=c.claimed_by) as claimed_by_lname,
(select first_name from tbl_users where id=c.claimed_to) as claimed_to_fname,
(select last_name from tbl_users where id=c.claimed_to) as claimed_to_lname 
from tbl_claims as c INNER JOIN tbl_users as u ON u.id = c.claimed_by INNER JOIN
tbl_users as u1 ON u1.id = c.claimed_to where claimed_by_fname like '%kotak%'

I know the above sql query is not efficient at all, i have just tried. It gives me record without where clause but does not work with where clause.

You don't need subselect just join

select c.*
      , u1.first_name claimed_by_fname 
      , u1.last_name claimed_by_lname
      , u2.first_name claimed_to_fname 
      , u2.last_nameclaimed_to_lname
from tbl_claims as c 
INNER JOIN tbl_users as u1 ON u1.id = c.claimed_by 
INNER JOIN tbl_users as u2 ON u2.id = c.claimed_to 
where u1.claimed_by_fname like '%kotak%'

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