-2

I'm making a social network-type web application.
I have a users table:

___________________________________________________
|user_id|firstname|lastname|password|email|country|
---------------------------------------------------

and a contacts table:

__________________________
|rel_id|user_id|friend_id|
--------------------------

The two tables are related on user_id.
How do I make a SQL query to retrieve all user's contacts?

qazerty23
  • 411
  • 2
  • 6
  • 16
  • 1
    You may want to consider reading a book on SQL or at least doing some minor research. This is a really trivial question. – Angelo Fuchs May 07 '14 at 12:48
  • 1
    more specifically read JOINS and you will find the answer !! – Abhik Chakraborty May 07 '14 at 12:48
  • possible duplicate of [Understanding how JOIN works when 3 or more tables are involved. \[SQL\]](http://stackoverflow.com/questions/1083676/understanding-how-join-works-when-3-or-more-tables-are-involved-sql) – Angelo Fuchs May 07 '14 at 12:51
  • Did you do any research before you asked this question? Lets start with the MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/join.html – Pred May 07 '14 at 12:51
  • I did consider using Join actually, but somewhy I had a doubht, so I asked here, sorry, I know it's a fundamental question. I haven't done programming for a while. – qazerty23 May 07 '14 at 12:53

1 Answers1

0

You can query as follows:

SELECT 
 u1.firstname || ' ' || u1.lastname as User,
 u2.firstname || ' ' || u2.lastname as Contact
FROM
 users u1
INNER JOIN contacts c
ON u1.user_id = c.user_id
INNER JOIN users u2
ON c.friend_id = u2.user_id;

Basically, you use JOINS. You may want to read more about them.

Reference:

A related SO question

Community
  • 1
  • 1
Joseph B
  • 5,519
  • 1
  • 15
  • 19
  • @GordonLinoff Thank you! The down-vote was probably a mistake, the new user still learning the ropes of SO. – Joseph B May 07 '14 at 12:52