MySQL查询问题

时间:2012-02-05 19:28:04

标签: mysql sql database

我有接下来的两个表:

     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 |
+----+-----------+---------+

我做了以下查询:

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

返回:

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

我现在的问题是......如何获取与这些ID关联的用户名(18和20)我应该向查询添加什么? (我不熟悉加入/联合和其他东西)

5 个答案:

答案 0 :(得分: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';

使用子查询应该表明出现问题。对于初学者来说,这很少是完成任务的最佳方式。这个(http://www.sql.co.il/books/tsqlfund2008/)对于初学者来说是一本非常好的书,尽管它是为MS SQL编写的,但98%也适用于MySQL。

答案 1 :(得分: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 :(得分: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 
        )

答案 3 :(得分: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
);

答案 4 :(得分:1)

你可以试试这个。

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 
    )