3

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)

5 Answers 5

3
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.

Sign up to request clarification or add additional context in comments.

Comments

2
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 
        )

Comments

2
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
  )

2 Comments

it's give me an error: "ERROR 1242 (21000): Subquery returns more than 1 row"
you are right, i've updated the answer to support more than a result
1
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
);

1 Comment

ERROR 1242 (21000): Subquery returns more than 1 row
1

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 
    )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.