Select Query to check both or either or condition

邮差的信 提交于 2019-12-02 15:19:33

问题


I'm using postgresql 9.1 and wish to select a single record from table. Details are as below :

table name : muser

fields present in table : userid,username,firstname,lastname,phonenumber and mailid

fields to be selected : userid, mailid, phonenumber

request parameter : mailid and phonenumber

conditions should be satisfied:

  1. display a record when both are present

  2. display a record when only mailid is present

  3. display a record when only phonenumber is present.

expected output:

single record (as userid is unique) with userid, phonenumber and mailid

both or any one if present.

i have tried the query as :

SELECT userid, mailid, phonenumber 
FROM muser 
WHERE phonenumber = ? OR mailid = ?

It's working fine for first two conditions but not working for last condition..When i fire query for last condition it gives all records present in query.Why so? Is their any changes in query? or anything else


回答1:


Assuming that when you mean "not present", mailid or phonenumber will be NULL in database,

SELECT userid, mailid, phonenumber 
FROM muser 
WHERE (phonenumber = ? AND (mailid IS NULL OR mailid = ''))
OR ((phonenumber IS NULL OR phonenumber = '') AND mailid = ?)
OR (phonenumber = ? AND mailid = ?)



回答2:


When I'm dealing with filter where the value can be any including null I'll try add coalesce()

SELECT userid, mailid, phonenumber 
FROM muser 
WHERE coalesce(phonenumber,'no data') = coalesce(?,'no data') 
OR coalesce(mailid,'no data') = coalesce(?, 'no data');


来源:https://stackoverflow.com/questions/24422963/select-query-to-check-both-or-either-or-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!