基本上你要求的是一种数据透视查询。
这里的技巧是使用 aCASE
在条件匹配或不匹配时提供列值NULL
,然后使用聚合函数,例如MAX()
将空值折叠成单行:
SELECT
MAX(CASE WHEN ms_workorder_events.start = 1 THEN ms_workorder_events.start ELSE NULL END) AS workStart
MAX(CASE WHEN ms_workorder_events.start = 2 THEN ms_workorder_events.start ELSE NULL END) AS qaStart
FROM
workorders
LEFT JOIN ms_workorder_events ON workorders.workOrderID = ms_workorder_events.workOrderID
为确保返回多行,您将需要列表中的更多列SELECT
和适当的GROUP BY
子句。例如:
SELECT
/* Retrieve row per workOrderID, for example */
workorder.workOrderID,
MAX(CASE WHEN ms_workorder_events.start = 1 THEN ms_workorder_events.start ELSE NULL END) AS workStart
MAX(CASE WHEN ms_workorder_events.start = 2 THEN ms_workorder_events.start ELSE NULL END) AS qaStart
FROM
workorders
LEFT JOIN ms_workorder_events ON workorders.workOrderID = ms_workorder_events.workOrderID
GROUP BY workorder.workOrderID
更新
要将上述内容合并到您的完整查询中,建议将LEFT JOIN
其作为派生表。在这种情况下,子查询中不需要连接,它可以单独完成,ms_workorder_events
因为它连接workorders
到外部查询中。
这是一个简短的示例:
SELECT
organizations.organizationName,
owner.firstName AS ownerFirstName,
/* ... Snip all other columns... */
workorders.title,
workorders.workOrderId,
/* ... Snip all other columns... */
/* Columns from subquery join */
eventType.workStart,
eventType.qaStart
FROM
workorders
LEFT JOIN users AS owner ON workorders.owner=owner.userID
/* ...Snip all your other joins...*/
LEFT JOIN (
SELECT
workOrderID,
MAX(CASE WHEN ms_workorder_events.start = 1 THEN ms_workorder_events.start ELSE NULL END) AS workStart
MAX(CASE WHEN ms_workorder_events.start = 2 THEN ms_workorder_events.start ELSE NULL END) AS qaStart
FROM ms_workorder_events
GROUP BY workorder.workOrderID
) eventType ON workorders.workOrderId = eventType.workOrderId
/* Etc... */