Multiple joins for user network

The following is query for user network. The problem is that I need one further step, to pull data from users for ids I get from network and here I am loosing how to do it.

userId | firstName | lastName …

who | whom

-Getting user networking (2nd degree - friends of friends)

k1.who AS who,
k2.who AS through1,
k2.whom AS whom
FROM knows AS k1 
LEFT JOIN knows AS k2 ON k1.whom=k2.who
WHERE k1.who = $userId

Now I am trying to make from this one further join, to get from users details for those ids. The following query is not ok but I don’t know how to fix it. Could somebody correct this query please or give me a tip what is wrong.

SELECT DISTINCT users.firstName, users.lastName,  
FROM (users LEFT JOIN users ON
LEFT JOIN knows as k1
ON knows.whom=k1.who
WHERE knows.who= '$userId'

thanks so much!

SELECT u1.userId    AS who_userId
     , u1.firstName AS who_firstName
     , u1.lastName  AS who_lastName 
     , u2.userId    AS whom_userId
     , u2.firstName AS whom_firstName
     , u2.lastName  AS whom_lastName 
  FROM users AS u1
  JOIN knows AS k
    ON k.who = u1.userId
  JOIN users AS u2
    ON u2.userId = k.whom
 WHERE u1.userId = $userId

Thanks. I tried also the below code 2 which works great. But the problem of both (yours and mine solution) is that I need only unique users. I tried this:

SELECT, users.firstName, users.lastName, k2.whom
FROM users

but in this way I get error Unknown column ‘k2.whom’ in ‘field list’ because I selected DISTINCT But I also need to show via who each person is related. So I need to pull from users information from whom and through1.

I think the best solution will be to create temporary table. Group by is too slow. Or is there any other solution?

And this is a code which is also solution to my previous problem:

k1.who AS who,
k2.who AS through1,
k2.whom AS whom
FROM (users INNER JOIN knows AS k2 ON 
LEFT JOIN knows AS k1 ON k1.whom=k2.who
WHERE k1.who=311

no, i’d be willing to bet that that is not the best solution

could you please show a few sample rows from each table, and then show what results you want from the query? i’m not sure i understand what you’re trying to do

I would like to get

where whom_userId must be distinct. So the only difference is about distinct.

Please provide some sample rows from the table along with expected output.

note that distinct works across ALL fields selected in the SELECT clause.