如何在查询中组合两个表?

时间:2009-07-17 06:02:41

标签: sql mysql join

我有两张桌子。首先是用户;这包括用户名和用户ID。第二个是由userid和query组成的搜索。

当我选择搜索表时,我想通过从用户表中获取数据来用username替换用户ID。这有意义吗?

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

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

有没有办法通过单个查询执行此操作?

3 个答案:

答案 0 :(得分:67)

您正在寻找inner join。这样就可以了:

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

答案 1 :(得分:3)

SELECT username, query FROM Users, Queries WHERE Users.userid=Queries.userid;

答案 2 :(得分:2)

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