AndreiBogdan
AndreiBogdan

Reputation: 11164

MySQL query problems

I have the next 2 tables:

     Users
+----+-----------+
| id | user_name |
+----+-----------+
| 18 | Andrei    |
| 19 | Gicu      |
| 20 | Gigel     |
+----+-----------+
         Requests
+----+-----------+---------+
| id | from_user | to_user |
+----+-----------+---------+
|  3 |        18 |      19 |
|  4 |        18 |      20 |
|  5 |        20 |      19 |
+----+-----------+---------+

And i make the following query:

SELECT requests.from_user 
 FROM requests 
  WHERE 
   (SELECT id FROM users WHERE users.user_name='Gicu')=requests.to_user;

which returns:

+-----------+
| from_user |
+-----------+
|        18 |
|        20 |
+-----------+

My question now is ... how to get the user names associated to these ids (18 and 20) What should i add to the query? (I'm not familiar to joins/union and those other stuff)

Upvotes: 3

Views: 118

Answers (5)

Ajay Kadyan
Ajay Kadyan

Reputation: 1079

you can try this.

SELECT u.user_name
FROM users u
WHERE u.id IN 
    (SELECT r.from_user 
     FROM requests r
     WHERE 
          (SELECT id 
           FROM users 
           WHERE user_name='Gicu')
     =r.to_user 
    )

Upvotes: 1

Gigi
Gigi

Reputation: 4962

SELECT users.user_name FROM users WHERE (SELECT users.id FROM users)=
  (SELECT requests.from_user 
   FROM requests 
   WHERE (SELECT id FROM users WHERE users.user_name='Gicu')=requests.to_user
  )

Upvotes: 2

Skyrel
Skyrel

Reputation: 226

SELECT users.user_name
FROM users
WHERE users.id IN 
        (SELECT requests.from_user 
         FROM requests 
         WHERE 
              (SELECT id 
               FROM users 
               WHERE users.user_name='Gicu')
         =requests.to_user 
        )

Upvotes: 2

Andrew
Andrew

Reputation: 4624

SELECT
  from.id, from.user_name
FROM Requests AS r
JOIN Users AS from ON from.id = r.from_user
JOIN Users AS to ON to.id = r.to_user
WHERE to.user_name LIKE 'Gicu';

Using a subquery should be a sign to you that something is wrong. It's rarely the best way for a beginner to get something done. This ( http://www.sql.co.il/books/tsqlfund2008/ ) is a very good book for beginners and though it's written for MS SQL, 98% of it applies to MySQL as well.

Upvotes: 3

Steven Leimberg
Steven Leimberg

Reputation: 785

Try this:

Select u.user_name
from Users u
where u.id = (
    SELECT requests.from_user 
    FROM requests 
    WHERE (SELECT id FROM users WHERE users.user_name='Gicu')=requests.to_user
);

Upvotes: 1

Related Questions