问题
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:
display a record when both are present
display a record when only mailid is present
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