Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Priority of an OR statement SQL

I have the following snippet code:

WHERE (Person.WorkGroupId = 2 or Person.RoleId = 2)

What I would like to happen is for this to return the first occurrence with a WorkGroupId of 2 on Person table. But, if there is not a person with a WorkgroupId of 2, then choose the first occurrence with RoldId of 2 on the Person table.

Thanks

like image 325
Bobcat88 Avatar asked Nov 29 '22 01:11

Bobcat88


1 Answers

SELECT TOP (1) * FROM 
(
  SELECT TOP (1) *, o = 1
  FROM Person
  WHERE WorkGroupId = 2 

  UNION ALL

  SELECT TOP (1) *, o = 2
  FROM Person 
  AND RoleId = 2
) AS x ORDER BY o;
like image 200
Lamak Avatar answered Dec 21 '22 23:12

Lamak