是否有任何替代方法来选择此case语句中的值而不是子查询

时间:2016-11-22 20:41:25

标签: mysql mariadb

我知道某种程度的MySQL,但我不确定是否有更正确的方式去做我在这里做的事情。

#Select Ticket ID, Ticket Title, Assigned To
SELECT * FROM
    (SELECT
        ti.number, ti.ticket_id, foev.value AS "ticket_name",
        CASE WHEN ti.staff_id = 0 AND ti.team_id = 0
            then
                "** Unassigned **"
            ELSE
                CASE when ti.staff_id = 0
                    THEN
                        (SELECT te.name FROM ost_team te WHERE te.team_id = ti.team_id)
                    ELSE
                        (SELECT CONCAT(st.firstname,LEFT(st.lastname,1)) FROM ost_staff st WHERE st.staff_id = ti.staff_id)
                    END
        END AS "assigned_to"
    FROM ost_ticket ti
        LEFT JOIN ost_form_entry foe ON foe.object_id = ti.ticket_id AND foe.object_type = "T" 
        LEFT JOIN ost_form_entry_values foev ON foev.entry_id = foe.id 
        GROUP BY ti.ticket_id) 
    AS ticket_meta_list 
ORDER BY ticket_id ASC;

是否有更正确的方法来执行这些子查询?我认为可能会有一些我不熟悉的联接。

1 个答案:

答案 0 :(得分:1)

如果您的员工表没有值为0的 staff_id ,并且您的团队表没有值为0的 team_id ,则可以将left joincoalesce结合使用SELECT ti.number, ti.ticket_id, foev.value AS ticket_name, COALESCE(CONCAT(st.firstname,LEFT(st.lastname,1)), te.name, '** Unassigned **') AS assigned_to FROM ost_ticket ti LEFT JOIN ost_form_entry foe ON foe.object_id = ti.ticket_id AND foe.object_type = 'T' LEFT JOIN ost_form_entry_values foev ON foev.entry_id = foe.id LEFT JOIN ost_team te ON te.team_id = ti.team_id LEFT JOIN ost_staff st ON st.staff_id = ti.staff_id GROUP BY ti.ticket_id ORDER BY ticket_id

print