如何连接3个表,其中一个表映射其他两个表的ID?

时间:2019-07-24 21:58:06

标签: mysql sql database

我试图在页面上显示与登录用户链接的每个文件,以显示有关该文件,用户以及该文件与谁有关的信息。

这是表格:

staff     users     map_file_users   files       category
id        id        id               id          id
pwd       name      file_id -------> ...         name
user_id-> ...  <--- user_id          category -->...

为此,我使用了这段代码,该代码显示了登录用户检索到的我需要的列后发布的每个文件:

SELECT info_client.name        AS client_name,
       info_client.surname     AS client_surname,
       info_staff.surname      AS staff_surname,
       info_staff.name         AS staff_surname,
       files.creation_date     AS file_creation_date,
       files.modification_date AS file_modification_date,
       files.size              AS file_size,
       files.type              AS file_type,
       category.name           AS file_category
FROM files
         INNER JOIN clients client      ON files.about_client = client.id
         INNER JOIN users info_client   ON info_client.id = client.user_id
         INNER JOIN staff staff         ON files.published_by = staff.user_id
         INNER JOIN users info_staff    ON info_staff.id = staff.user_id
         INNER JOIN categories category ON files.category = category.id
WHERE files.published_by = :id;

我不利用表“ map_file_staff”来显示链接到已登录用户的所有文件。该“ map_file_staff”表还可以让我通过简单地插入文件ID和/轻松地允许/禁止某人访问该文件。用户ID。

希望很清楚!

1 个答案:

答案 0 :(得分:0)

这是答案:

select staff.surname           as staff_surname,
       staff.name              as staff_name,
       files.title             as file_title,
       files.creation_date     as file_creation_date,
       files.modification_date as file_modification_date,
       files.size              as file_size,
       files.type              as file_type,
       category.name           as file_category,
       client.name             as client_name,
       client.surname           as client_surname

from map_file_user
         INNER JOIN users as staff on staff.id = map_file_user.user_id
         INNER JOIN files on files.id = map_file_user.file_id
         INNER JOIN categories category on files.category = category.id
         INNER JOIN clients c on files.about_client = c.id
         INNER JOIN users as client on client.id = c.id
WHERE map_file_user.user_id = 2;