简体   繁体   English

MySQL:根据用户联接四个表

[英]MySQL: Joining four tables based on user

After spending few hours yesterday, I decided to post here. 昨天花了几个小时后,我决定在这里发帖。 I have a database with few tables and I need to join 4 tables based on users table's idusers (id of user). 我有一个表很少的数据库,我需要根据用户表的idusers(用户ID)加入4个表。

Four tables that needs to be joined are: users, table1, table2 and table3. 需要联接的四个表是:用户,表1,表2和表3。

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

How they are related: - User signs up and the data is stored to users table: I need all fields from this table. 它们之间的关系: -用户注册并将数据存储到用户表:我需要该表中的所有字段。 - When they take an action, it gets stored in table1 (where users_idusers is users.idusers). -当他们执行操作时,该操作将存储在table1中(其中users_idusers是users.idusers)。 - Some actions (with comment) register to table2 (users_idusers is users.idusers). -一些操作(带有注释)注册到table2(users_idusers是users.idusers)。 - table1 and table2's a_id field is same and mapped to table3's custom_id3. -table1和table2的a_id字段相同,并映射到table3的custom_id3。

What I need: I want to be able to get all actions from table1 mapped to its user from the user table, table3 for lang and table2 (if there is a comment, get the text or return null for that field.). 我需要的是:我希望能够从用户表,映射到用户表,表3(用于lang和表2)的表1中获取映射到其用户的所有操作(如果有注释,请获取该字段的文本或返回null。)。

What my query looks like: 我的查询如下所示:

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);

The query above is missing the part that needs to join table2 and that's where I'm stuck. 上面的查询缺少需要加入table2的部分,这就是我遇到的问题。 Any help would be appreciated. 任何帮助,将不胜感激。

Thank you. 谢谢。

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]??

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

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