SQL Query Where Clause for Null OR Match (only ret

2019-08-14 19:21发布

问题:

I have a table that has records with a structure similar to this..

ID RoleID
1 NULL
2 15
3 16

I wrote a where clause to get records like the following

SELECT * from TableX 
WHERE (RoleID = 2 OR RoleID IS NULL)

This gets me the record of "1,NULL"

But if i query

SELECT * from TableX 
WHERE (RoleID = 15 OR RoleID IS NULL)

I get back "1,NULL" and "2,15".

Does anyone know how to structure a select to give me only one record? I only want "2,15" if 15 was passed and "1,NULL" if there are no matches.

Note, the actual query has MANY more where clauses to it, so nesting itself inside itself would be a very big query.

回答1:

How about SELECT TOP 1 with ORDER BY RoleID DESC

Here is a working example.

declare @mytable table
(
    ID int null,
    RoleID int null
)
insert @mytable values
(1, null),
(2, 15),
(3, 1)

select TOP 1 * 
from @mytable 
WHERE (RoleID = 2 OR RoleID IS NULL)
order by RoleID desc


select top 1 * from @mytable 
WHERE (RoleID = 15 OR RoleID IS NULL)
order by RoleID desc

Edit (edited based on comments received)
Note that the Insert statement works only for SQL Server 2008. For versions prior to 2008, you will have to break it into invidual inserts.



回答2:

order by RoleID limit 1


回答3:

SELECT TOP 1 * from TableX WHERE (RoleID = 15 OR RoleID IS NULL)
ORDER BY RoleID DESC