简体   繁体   中英

MySQL - How do I achieve my desired output with LEFT JOIN?

The following query:

   SELECT friendship.dom, friendship.sub,
          user.id, user.fname, user.lname
     FROM friendship
LEFT JOIN user ON friendship.dom = user.id

results in the following:

dom  sub  id  fname  lname 
---------------------------
2    1    2   Seun   Soti
1    2    1   Donal  Lynch

But how do I make the output look like:

dom  sub  id_dom  fname_dom  lname_dom  id_sub  fname_sub  lname_sub
----------------------------------------------------------------------
2    1    2       Seun       Soti       1       Donal      Lynch
1    2    1       Donal      Lynch      2       Seun       Soti

I just need both users ( dom and sub ) to be included in the output.

How about this:

SELECT 
  f.dom, f.sub,
  d.id dom_id, d.fname dom_fname, d.lname dom_lname,
  s.id sub_id, s.fname sub_fname, s.lname sub_lname
FROM friendship f
LEFT JOIN user d ON f.dom = d.id
LEFT JOIN user s ON f.sub = s.id

Try this:

SELECT friendship.dom, friendship.sub, user.id AS id_dom, ...
FROM friendship
LEFT JOIN user ON friendship.dom = user.id

That should work for you. HTH

 SELECT friendship.dom, friendship.sub,
      user.id, user.fname, user.lname,
      u1.id, u1.fname, u1.lname
 FROM friendship 
 FROM friendship
 LEFT JOIN user ON friendship.dom = user.id 
 LEFT JOIN user as u1 ON friendship.sub = u1.id

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