LEFT JOIN,INNER JOIN和UNIONS,如何订购

时间:2017-05-16 03:14:13

标签: mysql

我们有一个生成报告的SQL查询。我们已经成功地加入了我们的设置表来使用正确的项更新整数值。我们还使用了一个联合来显示我们的三种类型的用户。

我们希望接受此查询并通过e_job.objId字段对其进行排序,但是我们发现使用多个连接和联合非常困难。

如果有人能提供帮助,我们将不胜感激。

SELECT e_job.objId AS 'Job Number', e_student.Lastname AS 'Last Name', e_student.Name AS 'First Name', e_asset.objId AS 'Asset Number', e_asset.aSerialNumber AS 'Serial Number', si.sLabel AS 'Issue', srt.sLabel AS 'Repair Type', ss.sLabel As 'Status', e_job.note 'Description',FROM_UNIXTIME(e_job.jCreatedAt,'%d/%m/%y') AS 'Date Created'
                FROM e_job
                INNER JOIN e_student ON e_job.jName = e_student.username
                INNER JOIN e_asset ON e_job.jAsset = e_asset.aId
                LEFT JOIN e_settings si ON si.sKey = 'job_issue' AND si.sValue = e_job.jIssue
                LEFT JOIN e_settings srt ON srt.sKey = 'job_rep_type' AND srt.sValue = e_job.jRepairType
                LEFT JOIN e_settings ss ON ss.sKey = 'job_status' AND ss.sValue = e_job.jStatus
                WHERE jStatus = 1 && jRepairType = 2
                UNION
                SELECT e_job.objId AS 'Job Number', e_teachers.Lastname AS 'Last Name', e_teachers.Name AS 'First Name', e_asset.objId AS 'Asset Number', e_asset.aSerialNumber AS 'Serial Number', si.sLabel AS 'Issue', srt.sLabel AS 'Repair Type', ss.sLabel As 'Status', e_job.note 'Description',FROM_UNIXTIME(e_job.jCreatedAt,'%d/%m/%y') AS 'Date Created'
                FROM e_job
                INNER JOIN e_teachers ON e_job.jName = e_teachers.username
                INNER JOIN e_asset ON e_job.jAsset = e_asset.aId
                LEFT JOIN e_settings si ON si.sKey = 'job_issue' AND si.sValue = e_job.jIssue
                LEFT JOIN e_settings srt ON srt.sKey = 'job_rep_type' AND srt.sValue = e_job.jRepairType
                LEFT JOIN e_settings ss ON ss.sKey = 'job_status' AND ss.sValue = e_job.jStatus
                WHERE jStatus = 1 && jRepairType = 2
                UNION
                SELECT e_job.objId AS 'Job Number', e_supportStaff.Lastname AS 'Last Name', e_supportStaff.Name AS 'First Name', e_asset.objId AS 'Asset Number', e_asset.aSerialNumber AS 'Serial Number', si.sLabel AS 'Issue', srt.sLabel AS 'Repair Type', ss.sLabel As 'Status', e_job.note 'Description',FROM_UNIXTIME(e_job.jCreatedAt,'%d/%m/%y') AS 'Date Created'
                FROM e_job
                INNER JOIN e_supportStaff ON e_job.jName = e_supportStaff.username 
                INNER JOIN e_asset ON e_job.jAsset = e_asset.aId
                LEFT JOIN e_settings si ON si.sKey = 'job_issue' AND si.sValue = e_job.jIssue
                LEFT JOIN e_settings srt ON srt.sKey = 'job_rep_type' AND srt.sValue = e_job.jRepairType
                LEFT JOIN e_settings ss ON ss.sKey = 'job_status' AND ss.sValue = e_job.jStatus
                WHERE jStatus = 1 && jRepairType = 2

谢谢

1 个答案:

答案 0 :(得分:1)

如果在查询末尾添加ORDER BY子句,它应该应用于整个结果集。您可以尝试添加此内容:

ORDER BY `Job Number`

此外,您不需要在第一个以外的联合查询中指定别名。第一组别名是什么棒。