MySQL:根据用户连接四个表

标签 mysql sql join left-join

昨天花了几个小时后,我决定在这里发帖。我有一个只有几个表的数据库,我需要根据用户表的 idusers (用户 ID)连接 4 个表。

需要连接的四个表是:users、table1、table2 和 table3。

users
idusers, name, email, a, b, c, etc.

table1 
custom_id1, a_id, users_idusers

table2 
custom_id2, a_id, users_idusers, comment

table3 
custom_id3, lang

它们之间的关系: - 用户注册并将数据存储到用户表中:我需要该表中的所有字段。 - 当他们采取操作时,它会存储在 table1 中(其中 users_idusers 是 users.idusers)。 - 一些操作(带注释)注册到表2(users_idusers 是users.idusers)。 - table1和table2的a_id字段相同并映射到table3的custom_id3。

我需要什么: 我希望能够从用户表中获取映射到其用户的 table1 中的所有操作,为 lang 获取 table3 和 table2(如果有注释,则获取该字段的文本或返回 null。)。

我的查询是什么样的:

SELECT table1.a_id, table1.users_idusers, users.*, table3.langkey
    FROM table1
    LEFT JOIN users ON (users.idusers = table1.users_idusers)
    LEFT JOIN table3 ON (table1.a_id = table3.custom_id3);

上面的查询缺少需要连接 table2 的部分,这就是我陷入困境的地方。任何帮助将不胜感激。

谢谢。

最佳答案

SELECT u.*
     , and
     , some
     , other
     , columns
  FROM users u
  JOIN table1 a
    ON a.users_idusers = u.idusers
  JOIN table3 l
    ON l.custom_id3 = a.a_id
  LEFT
  JOIN table2 c
    ON c.a_id = a.a_id
  [AND c.users_idusers = a.users_idusers]??

关于MySQL:根据用户连接四个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701009/

相关文章:

android - 如何在 POST 后以正确的编码在 Flask 中返回 json

php - 多个日期选择器实例,更新数据库

mysql - 如何使用mysql查询检索精确字符串匹配的记录?

mysql - 从经度和纬度坐标获取邮政编码

c# - 每个查询一个新的 sql 连接?

MySQL选择数据对

javascript - jquery - 找到整数或空格时拆分(即拆分类(class)代码)

python - 使用私钥使用 Pythondb 进行 SSH

java - 使用 Hibernate 连接不同数据库中的 2 个表

MySQL 查询带有别名的 INNER JOIN