选择null或not null取决于参数

时间:2015-11-09 04:12:02

标签: mysql sql

我有这样的查询:

    SELECT old.NPP,
       old.NAMA,
       old.JOB,
       pgh.status
    FROM a old
    LEFT JOIN b pgh ON old.person_id = pgh.person_id
                    AND pgh.periode = 2015
                    AND pgh.LAST_STATUS = 1
    WHERE old.UNIT_BESARAN = 'DIVISI TEKNOLOGI INFORMASI'
    AND pgh.status = #status
    ORDER BY pgh.status

我希望我的查询可以从pgh状态获取每个值,就像我输入状态5时,查询必须返回状态为5,但是当我输入null时,查询将在状态为null时从数据库返回数据。

如何设置查询?

2 个答案:

答案 0 :(得分:1)

你可以这样写条件:

where old.UNIT_BESARAN = 'DIVISI TEKNOLOGI INFORMASI' and
      (pgh.status = #status or pgh.status is null and #status is null)

答案 1 :(得分:0)

如果我理解你的情况,我认为有空字符串,所以要确保条件是正确的。只需使用ISNULL

SELECT old.NPP,
       old.NAMA,
       old.JOB,
       pgh.status
FROM a old
     LEFT JOIN b pgh ON old.person_id = pgh.person_id
                    AND pgh.periode = 2015
                    AND pgh.LAST_STATUS = 1
WHERE old.UNIT_BESARAN = 'DIVISI TEKNOLOGI INFORMASI' 
AND pgh.status = ISNULL(#status,'') 
ORDER BY pgh.status