2012-02-05 120 views
3

我有未來2個表:MySQL查詢問題

 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)我應該向查詢添加什麼? (我不熟悉的加入/工會和那些其他的東西)

回答

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

我愛stackoverflow.com:D – AndreiBogdan 2012-02-05 19:49:39

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

這是給我的錯誤:「ERROR 1242(21000):子查詢返回多個1行」 – AndreiBogdan 2012-02-05 19:36:24

+1

你是對的,我已經更新了答案相比,它支持的結果 – Gigi 2012-02-05 19:45:38

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 
); 
+0

ERROR 1242(21000)更多:子查詢返回多於一行 – AndreiBogdan 2012-02-05 19:38:21

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

你可以試試這個。

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 
    )