简体   繁体   中英

Get ID from database matching multiple names

I have database with columns

ID FirstName LastName. I would like get the id of various people. Hence I am writing queries like the below.

Select ID from Database where FirstName='X' and LastName='x1'
Select ID from Database where FirstName='Y' and LastName='y1'
Select ID from Database where FirstName='Z' and LastName='z1'

I there any way to optimize this query.

You can simply put multiple condition in single where clause so just use them for simplicity.

Select ID from Database 
where (FirstName='X' and LastName='x1') OR 
      (FirstName='Y' and LastName='y1') OR
      (FirstName='Z' and LastName='z1')

with NULL Entries- You can add one more condition

  OR (FirstName is NULL AND LastName is NULL)

If you want to get row even for those name which are not exists in your Database table (don't use this name for your table, BTW):

select a.FirstName, a.LastName, d.id
from (
    select 'X', 'X1' union all
    select 'Y', 'Y1' union all
    select 'Z', 'Z1'
) as a(FirstName, LastName)
    left outer join Database as d on d.FirstName = a.FirstName and d.LastName = a.LastName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM