0

I'm struggling to find out a solution for my select statement. I have two tables:

CREATE TABLE Things
(
  Id int, 
  type int
)

CREATE TABLE Relations
(
  Id int,
  IdParent int,
  IdChild int
)

What I need to select, based on given Thing Id:

  • All records from Things that has Type = -1
  • All records from Things that has Type matching IdChild where IdParent is Type of a row matching given Id.
  • If Type of a row matching given Id is -1 or doesn't exist in table Relations (as IdParent) I need to select all records from Things

I am having problem with the last scenario, I tried to do that by joining Relations table, but I can't come up with a condition that would satisfy all scenarios, any suggestions?

UPDATE

This is how I do it now. I need to solve the scenario where given id does not exists in table Relations - then I need to select all records.

CREATE TABLE Things (id int, type int)
CREATE TABLE Relations (id int, parent int, child int)

INSERT INTO Things VALUES (1, 1)
INSERT INTO Things VALUES (2, -1)
INSERT INTO Things VALUES (3, 3)
INSERT INTO Things VALUES (4, 3)
INSERT INTO Things VALUES (5, 2)
INSERT INTO Things VALUES (6, -1)

INSERT INTO Relations VALUES (1, 1, 2)

DECLARE @id int = 1

SELECT * FROM Things
JOIN Relations R ON R.parent = @id AND Type = R.child OR Type = -1

So I must solve the situation where @id = 2 for example - I need to retrieve all rows (same for @id = 5, unless it appears in Relations in parent column somewhere).

UPDATE 2

I came up with something like that:

DECLARE @id int = 2
DECLARE @type int

SELECT @type = type FROM Things WHERE Id = @id

IF @type > -1
BEGIN
SELECT T.* FROM Things T
JOIN Relations R ON (R.parent = @id AND T.Type = R.child) OR T.Type = -1
END
ELSE
BEGIN
SELECT * FROM Things
END

I'm quite sure that this can be done differently, without conditional IF, optimized.

pzaj
  • 1,062
  • 1
  • 17
  • 37

1 Answers1

0
 from Things
 left outer join Relations 
   on Relations.IdParent = Things.Type 
where Things.Type = -1 or Relations.IdParent is null 
paparazzo
  • 44,497
  • 23
  • 105
  • 176