DROP VIEW ticket_messages_export_view;

CREATE VIEW ticket_messages_export_view AS
SELECT
    m.id,
    m.ticket_id,

    projects.name    AS project,
    channels.title   AS channel,
    categories.title AS category,

    m.client_id,
    clients.name     AS client,
    users.name       AS "user",
    users.email      AS user_email,

    m.type,
    m.text,

    m.received,
    m.[read],
    m.deleted,
    tickets.created_at as ticket_created_at,
    m.created_at as sent_at,
    m.received_at,
    m.read_at

FROM ticket_messages m
         LEFT JOIN tickets ON tickets.id = m.ticket_id
         LEFT OUTER JOIN projects ON projects.id = tickets.project_id
         LEFT OUTER JOIN channels ON channels.id = tickets.channel_id
         LEFT OUTER JOIN categories ON categories.id = tickets.category_id

         LEFT OUTER JOIN files ON files.id = m.file_id
         LEFT OUTER JOIN clients ON clients.id = m.client_id
         LEFT OUTER JOIN users ON users.id = m.user_id;

