CREATE VIEW desks_data_base AS
SELECT
    desks.desk_id AS desk_id,
    desks.user_id AS user_id,
    desks.desk_code AS desk_code,
    desks.parent_desk AS parent_desk,
    desks.tree AS tree,
    desks.import_open AS import_open,
    desks.import_source as import_source,
    desks.link_id as link_id,
    desks.record_desk  AS record_desk,
    IF (
        desks_parents.desk_id IS NOT NULL,
        'parent',
        IF (
            desks_subs.desk_id IS NOT NULL,
            'sub',
            'empty'
        )
    ) AS type_desk,
    IF (
        desks_parents.desk_id IS NOT NULL,
        0,
        link_id
    ) AS import_cards,
    IF (
        desks_subs.desk_id IS NOT NULL,
        0,
        link_id
    ) AS import_desks
FROM
    desks
    LEFT JOIN (
        -- parents
        SELECT
            DISTINCT desks.parent_desk AS desk_id
        FROM
            desks
    ) desks_parents ON desks.desk_id = desks_parents.desk_id
    LEFT JOIN (
        -- subs
        SELECT
            DISTINCT desks.desk_id AS desk_id
        FROM
            desks
            JOIN cards ON desks.desk_id = cards.desk_id
    ) desks_subs ON desks.desk_id = desks_subs.desk_id