SQL查询结果,其中Join具有NULL结果

时间:2013-09-30 16:53:20

标签: sql sql-server-2008-r2

我想知道你是否可以提供帮助 - 我已经创建了一个SQL查询(SQLServer),虽然有些结果没有显示,我认为它是由于某些连接上的NULL结果。例如,我知道一些连接将使用NULL结果,因为100.resp_unit_no可能是NULL以及100.employee_no。

到目前为止的查询是:

select 
058.DESCRIPTION "IRU",
111.job_ref "Job Reference",
117.DESCRIPTION "Status",
108.STATUS "Fixed?",
105.DESCRIPTION "Job Type",
111.POSTCODE "Postcode",
111.site_id "Site ID",
108.CONTRACT_START "Contract Earliest",
108.CONTRACT_COMPLETION "Contract Latest",
108.BOOKED_DURATION "Planned Duration (mins)",
111.IMPORTANCE "Importance",
111.CUSTOMER_NAME "Customer Name",
100.expected_start "Expected Start",
100.expected_end "Expected End",
210.NAME "Employee",
111.ON_HOLD "On Hold?"
FROM 
111_JOBS 111,
108_JOB_DETAILS 108,
058_RESPONSIBILITY_UNITS 058,
100_ACTIVITIES 100,
105_ACTIVITY_TYPES 105,
210_EMPLOYEES 210,
117_STATUS_DESCRIPTIONS 117
where 111.JOB_NO=108.JOB_NO
AND 111.JOB_NO=100.JOB_NO
AND 100.RESP_UNIT_NO=058.RESP_UNIT_NO
AND 111.JOB_TYPE=105.ACTIVITY_TYPE
AND 210.EMPLOYEE_NO=100.EMPLOYEE_NO
AND 117.STATUS=100.ACTIVITY_STATUS
order by IRU, Employee, EXPECTED_START;

我认为我需要一个正确的外连接,但我不能让结构正确...

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

如果您更改查询以使用ANSI-92显式连接语法而不是您正在使用的ANSI-89语法(因为名称建议超过20年的日期),那么您查询将变得更容易操纵:

SELECT  058.DESCRIPTION "IRU",
        111.job_ref "Job Reference",
        117.DESCRIPTION "Status",
        108.STATUS "Fixed?",
        105.DESCRIPTION "Job Type",
        111.POSTCODE "Postcode",
        111.site_id "Site ID",
        108.CONTRACT_START "Contract Earliest",
        108.CONTRACT_COMPLETION "Contract Latest",
        108.BOOKED_DURATION "Planned Duration (mins)",
        111.IMPORTANCE "Importance",
        111.CUSTOMER_NAME "Customer Name",
        100.expected_start "Expected Start",
        100.expected_end "Expected End",
        210.NAME "Employee",
        111.ON_HOLD "On Hold?"
FROM    111_JOBS 111
        INNER JOIN 108_JOB_DETAILS 108
            ON 111.JOB_NO = 108.JOB_NO
        INNER JOIN 100_ACTIVITIES 100
            ON 111.JOB_NO = 100.JOB_NO
        LEFT JOIN 058_RESPONSIBILITY_UNITS 058          
            100.RESP_UNIT_NO = 058.RESP_UNIT_NO
        LEFT JOIN 105_ACTIVITY_TYPES 105
            ON 111.JOB_TYPE = 105.ACTIVITY_TYPE
        LEFT JOIN 210_EMPLOYEES 210
            ON 210.EMPLOYEE_NO = 100.EMPLOYEE_NO
        LEFT JOIN 117_STATUS_DESCRIPTIONS 117
            ON 117.STATUS = 100.ACTIVITY_STATUS
ORDER BY IRU, Employee, EXPECTED_START;

现在,在不知道哪些列可能为null的情况下,我不知道要从INNER更改为LEFT的哪些联接,所以我只更改了其中一些,但您应该能够根据需要改变一些。

Aaron Bertrand写了一个good article,更有理由转换到更新的连接语法。