【问题标题】:Correct way to join user table to content table?将用户表连接到内容表的正确方法?
【发布时间】:2015-08-25 20:48:20
【问题描述】:

所以我有两张桌子。

一个存储用户,名为user

id     date_joined      username
1      2014-12-12       UserA
2      2014-11-11       UserB

还有一个存储内容,命名为article

id     user_id      date           content
1      1            2014-10-10     content here
2      1            2014-11-10     content here
3      2            2014-12-10     content here
4      1            2014-13-10     content here

查询此数据以获取每个用户的用户名以及内容的正确方法是什么?

我目前有这个:

SELECT user.username, article.date, article.content
FROM article
LEFT JOIN user ON user.id = article.user_id
ORDER BY article.date

这可行,但完全是猜测。这是正确的查询吗?我是否需要所有元素中的user.article.?还是只为LEFT JOIN 位?

那么这也是正确/推荐的吗?

SELECT username, date, content
FROM article
LEFT JOIN user ON user.id = article.user_id
ORDER BY date

【问题讨论】:

    标签: mysql join left-join


    【解决方案1】:

    您需要 table.column 语法仅在两者都有同名列的情况下。如果只有一个选项 - 不需要(尽管在我看来使查询更清晰)

    至于查询本身 - 这很好,但你需要知道一件事(并决定你想要什么,从你的问题中不清楚) - 左连接或内连接。 内连接 - 只会给你两个表中都存在的结果(即 - 如果 user_id 3 存在于文章而不是用户 - 你不会得到它。左连接 - 在这种情况下,你将获得 user_id 3 记录,其中的值来自文章表,以及用户表列上的空值 所以这取决于需要决定哪个,但基本上你的查询很好

    【讨论】:

      【解决方案2】:

      我喜欢为表名使用别名。我认为它使阅读更容易。使用 RIGHT JOIN 它将返回右表(文章)中也存在于右表(文章)中的所有内容。

      SELECT u.username, a.date, a.content
      FROM article AS a
      RIGHT JOIN user AS u
      ON u.id = a.user_id
      ORDER BY a.date
      

      LEFT JOIN 只会生成左表(用户)中的 id 匹配项

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 1970-01-01
        • 2020-02-03
        • 1970-01-01
        • 2017-08-16
        相关资源
        最近更新 更多