返回整个表的位置

时间:2019-03-04 02:43:52

标签: sql

问题:如果value ='0'或NULL,如何忽略WHERE参数

返回的列之一显示0,这导致我的查询出现问题。

我遇到的问题在于p.author值。有时它与pe.system_id匹配,但有时是0NULL。如果p.author0。如果我注释掉and参数,那么它将为docsadm.people pe1中的每个条目返回一行,否则将不返回任何一行,因为没有条目= 0

SELECT 
    p.docnumber, p.docname, p.abstract, d.type_id, a.application, 
    pe1.full_name as 'Author', pe.full_name as 'Registered by',
    convert(varchar(10), p.pif_letter_date + 0.4166666,111) as 'Date written', 
    convert(varchar(10), p.creation_date + 0.4166666,111) as 'Registered on', 
    convert(varchar(10), p.last_edit_date + 0.4166666,111) as 'Last edit date', 
    f.pd_filept_no, f.pd_file_name, f.pd_title, sm.pif_marking, s.pd_section_code,
    p.status as 'Availability', p.related, p.kmc_old_docno
FROM 
    docsadm.profile p, docsadm.pd_file_part f, docsadm.people pe, 
    docsadm.people pe1, docsadm.apps a, docsadm.documenttypes d, 
    docsadm.pif_sec_mark sm, docsadm.pd_section s
WHERE 
    p.DOCNUMBER IN ('5451326')
    AND p.pd_file_part = f.system_id
    AND p.typist = pe.system_id
    AND p.author = pe1.system_id --Problem Line
    AND p.application = a.system_id
    AND p.documenttype = d.system_id
    AND f.kmc_ptto_sec_mark = sm.system_id
    AND f.pd_pttosec_link = s.system_id
    AND p.item_type IN ('D','E','M','F')
ORDER BY
    5, 4, 1

2 个答案:

答案 0 :(得分:2)

有很多方法,但是我更喜欢使用JOIN .. ON语法,并在表中包含LEFT OUTER JOIN(LEFT JOIN)的可选数据部分。

  SELECT p.docnumber,
         p.docname, 
         p.abstract, 
         d.type_id, 
         a.application, 
         pe1.full_name as 'Author', 
         pe.full_name as 'Registered by',
         convert(varchar(10), p.pif_letter_date + 0.4166666,111) as 'Date written', 
         convert(varchar(10), p.creation_date + 0.4166666,111) as 'Registered on', 
         convert(varchar(10), p.last_edit_date + 0.4166666,111) as 'Last edit date', 
         f.pd_filept_no, 
         f.pd_file_name, 
         f.pd_title, 
         sm.pif_marking, 
         s.pd_section_code,
         p.status as 'Availability', 
         p.related, 
         p.kmc_old_docno

    FROM docsadm.profile p
    JOIN docsadm.pd_file_part f
      ON p.pd_file_part = f.system_id
    JOIN docsadm.people pe
      ON p.typist = pe.system_id
    JOIN docsadm.apps a
      ON p.application = a.system_id
    JOIN docsadm.documenttypes d
      ON p.documenttype = d.system_id
    JOIN docsadm.pif_sec_mark sm
      ON f.kmc_ptto_sec_mark = sm.system_id
    JOIN docsadm.pd_section s
      ON f.pd_pttosec_link = s.system_id
    LEFT
    JOIN docsadm.people pe1
      ON p.author = pe1.system_id --Problem Line

    WHERE p.DOCNUMBER in ('5451326')
      and p.item_type in ('D','E','M','F')
    ORDER by 5, 4, 1

答案 1 :(得分:1)

...
和((p.author为null)或(p.author ='0')或(p.author = pe1.system_id))
...

...工作吗?

如果p.author为null或p.author = 0,它将把“ and ...”变成“ and true”