简体   繁体   English

如何在MySQL中使用正确的外部联接将三个单独的列联接在一起?

[英]How do you use right outer join to join three separate columns together in mysql?

Write a SQL RIGHT OUTER JOIN statement that joins the user_id column from the blog.posts table, the name column of the blog.users table and the body column of the blog.posts table together. 编写一条SQL RIGHT OUTER JOIN语句,该语句将blog.posts表中的user_id列,blog.users表的name列和blog.posts表的body列连接在一起。

Here is what I have so far: 这是我到目前为止的内容:

USE blog;
SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON
    posts.user_id, posts.body = users.name;

Here are the tables with their columns 这是表格及其栏

posts: id,body,user_id
users: id, name

How do I adjust this code to work? 如何调整此代码以使其正常工作?

Here is the syntax for RIGHT JOIN. 这是RIGHT JOIN的语法。

SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

For more details, go to this link. 有关更多详细信息,请转到此链接。

https://www.w3schools.com/sql/sql_join_right.asp https://www.w3schools.com/sql/sql_join_right.asp

Hope this helps. 希望这可以帮助。

to stick with a right join then: 坚持正确的加入,然后:

SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON posts.user_id = users.id;

but, more conventionally that is the same at this: 但是,按照惯例,这是相同的:

SELECT posts.user_id, posts.body, users.name
  FROM users
    LEFT OUTER JOIN posts ON users.id = posts.user_id;

However, I am going to hope you cannot have a blog without a user, so my guess is it really should be an inner join: 但是,我希望您没有用户也无法拥有一个博客,因此我想它确实应该是一个内部联接:

SELECT posts.user_id, posts.body, users.name
  FROM posts
    INNER JOIN users ON posts.user_id = users.id;

You can try like the following: 您可以尝试如下操作:

SELECT posts.user_id, posts.body, COALESCE(users.name, 'Unknown') AS user_name
  FROM Posts
       LEFT JOIN Users
          ON Posts.user_id = Users.id

This worked for me 这对我有用

USE blog;
SELECT posts.user_id, posts.body, users.name
FROM posts
RIGHT OUTER JOIN users ON
posts.user_id = users.id;

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM