Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutually Exclusive Queries

Question

How would you role an IF...ELSE that produces mutually exclusive results into a query that produces the same results?

Use Case

As the principal (currently logged in user) I can get a list of users in my organization. If I'm assigned to any departments then the list of users is a smaller set that are assigned to the same departments.

Example

DECLARE @organizationId int = 421;
DECLARE @userId int = 1138;

IF EXISTS (SELECT * FROM dbo.DepartmentsUsers WHERE organizationId = @organizationId AND userId = @userId)
  -- Get user IDs in the same department(s) as the principal.
  SELECT du.userId
  FROM dbo.DepartmentsUsers AS du
  JOIN (
        -- Get department IDs assigned to the principal.
        SELECT departmentId
        FROM dbo.DepartmentsUsers
        WHERE organizationId = @organizationId
          AND userId = @userId) AS j
    ON du.departmentId = j.departmentId
  WHERE du.organizationId = @organizationId
ELSE
  -- Get all user IDs in the organization.
  SELECT userId
  FROM dbo.OrganizationsUsers
  WHERE organizationId = @organizationId
like image 430
James Schmidt Avatar asked Oct 20 '25 12:10

James Schmidt


1 Answers

Use a union with the "if" condition added to each where clause:

SELECT du.userId
FROM dbo.DepartmentsUsers AS du
JOIN (  SELECT departmentId
        FROM dbo.DepartmentsUsers
        WHERE organizationId = @organizationId
          AND userId = @userId) AS j
    ON du.departmentId = j.departmentId
WHERE du.organizationId = @organizationId
AND EXISTS (SELECT * FROM dbo.DepartmentsUsers WHERE organizationId = @organizationId AND userId = @userId)
UNION
SELECT userId
FROM dbo.OrganizationsUsers
WHERE organizationId = @organizationId
AND NOT EXISTS (SELECT * FROM dbo.DepartmentsUsers WHERE organizationId = @organizationId AND userId = @userId)
like image 137
Bohemian Avatar answered Oct 23 '25 02:10

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!