如何使这三个表的MySQL查询工作?

时间:2014-05-01 14:45:02

标签: mysql

我有以下数据库方案:


内容:

+----+--------+---------+
| id |  name  | user_id |
+----+--------+---------+
|  1 | name11 |      23 |
|  2 | name22 |      34 |
|  3 | name33 |      45 |
+----+--------+---------+

“用户”列包含用户ID


标签:

+----+------------+--------+
| id | content_id | tag_id |
+----+------------+--------+
|  1 |          1 |      1 |
|  2 |          1 |      4 |
|  3 |          1 |      5 |
|  4 |          2 |      3 |
|  5 |          2 |      4 |
|  6 |          2 |      5 |
|  7 |          2 |      7 |
|  8 |          3 |      2 |
+----+------------+--------+

每个内容都有多个标签


用户:

+----+---------+--------------+
| id |  name   |     rank     |
+----+---------+--------------+
| 23 | James   | beginner     |
| 34 | Arthur  | professional |
| 45 | Gosling | newbie       |
+----+---------+--------------+

我要做的是获取具有特定标记的所有内容以及内容创建者的用户名+排名。

因此,例如,如果我请求标记5(内容1和2包含标记5),则查询应返回:

+------------+--------------+------------+--------------+--------------+
| content_id | content_name | creator_id | creator_name | creator_rank |
+------------+--------------+------------+--------------+--------------+
|          1 | name11       |         23 | James        | beginner     |
|          2 | name22       |         34 | Arthur       | professional |
+------------+--------------+------------+--------------+--------------+

我试过的是

SELECT content.id, content.name, content.user_id, users.name, users.rank
FROM tags 
JOIN content, users 
WHERE tags.tag_id = 5 AND users.id = content.user_id

但那没用。

3 个答案:

答案 0 :(得分:2)

始终使用正确的连接:

SELECT t.content_id, c.name content_name, c.user_id creator_id, u.name creator_name, u.rank creator_rank
FROM tags t
JOIN content c ON c.id = t.content_id  
JOIN users u ON u.id = c.user_id
WHERE t.tag_id = 5

“现代”连接语法已经存在了20多年。

答案 1 :(得分:1)

试试这个:

SELECT C.id as content_id, C.name as content_name, C.user_id as creator_id, U.name as creator_name, U.rank as creator_rank
FROM tags T INNER JOIN content C
    ON T.content_id = C.id
INNER JOIN users U
    ON C.user_id = U.id
WHERE T.tag_id = 5

这应该有效

答案 2 :(得分:0)

SELECT
    content.id,
    content.name,
    content.user_id,
    users.name,
    users.rank
FROM
    tags
JOIN content
JOIN users 
ON tags.tag_id = 5
AND users.id = content.user_id
AND content.id = tags.content_id;

您忘记了content.id = tags.content_id。 此外,您应该使用ON运算符代替WHERE加入{{1}}。