mysql - 对于此类问题,如何使用左连接编写 mySQL?

标签 mysql left-join

如何使用左连接构建 mySQL 查询来解决此问题?

Feed Table
-id
-lastpost_id (The id of the user from USER TABLE who last posted)
-firstpost_id (The id of the user from USER TABLE who first posted)

User Table
-id
-name

我想要一张这样的 table

Result 
-id
-lastpost_id
-lastpost_name
-firstpost_id
-firstpost_name

最佳答案

select *, a.name as lastpost_name, b.name as firstpost_name from Feed f 
      left join user a on f.lastpost_id=a.id 
      left join user b on f.firstpost_id=b.id

技巧是左连接,然后将表别名为 a 或 b。这样您就可以对同一个表进行多个联接

关于mysql - 对于此类问题,如何使用左连接编写 mySQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239475/

相关文章:

mysql - 如何使用 "LEFT ON"获取SQLite中的数据

mysql - LEFT JOIN 与主查询的相对值

mysql - 查找序列中的错误

php - Mysql数据库只进入一次

mysql - 非常慢的 mysql 查询 : left join multiple table and where clause for each table

php - LEFT JOIN,如果存在第二个表的结果,则添加到 PHP 中的数组

数据库 |左加入 wp_posts 和 wp_postmeta

mysql - sql:获取稍微修改的查询以及 sql select 查询的计数?

php - COUNT 个返回数组?

php - Laravel 在 leftjoin 处分页