Reputation: 11164
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
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
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
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
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
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