2009-07-17 46 views
13

我有兩張桌子。首先是用戶;這包括用戶名和用戶ID。第二個是由用戶標識和查詢組成的搜索。如何在查詢中組合兩個表?

當我選擇搜索表時,我希望通過從用戶表獲取數據,以用戶名替換用戶ID。這是有道理的嗎?

+-------+----------+ 
|userid | username | 
+-------+----------+ 
| 1 | foo1 | 
+-------+----------+ 
| 2 | foo2 | 
+-------+----------+ 
| 3 | foo3 | 
+-------+----------+ 
| 4 | foo4 | 
+-------+----------+ 

+-------+----------+ 
|userid | query | 
+-------+----------+ 
| 1 | blah1 | 
+-------+----------+ 
| 2 | blah2 | 
+-------+----------+ 
| 3 | blah2 | 
+-------+----------+ 
| 4 | blah2 | 
+-------+----------+ 

有沒有辦法做到這一點與單個查詢?

回答

63

您正在查找inner join。這將做到這一點:

SELECT s.query, u.username 
FROM search s 
INNER JOIN users u 
ON s.userid = u.userid 
+13

嗯,這是一個奇怪的downvote ... – 2009-07-17 06:10:11

2
SELECT u.`username`, s.`query` 
    FROM `search` s 
     INNER JOIN `users` u ON s.`userid` = u.`userid` 
3
SELECT username, query FROM Users, Queries WHERE Users.userid=Queries.userid;