sql server - MS SQL select statement with "check table" -


i'm struggling find out solution select statement. have 2 tables:

create table things (   id int,    type int )  create table relations (   id int,   idparent int,   idchild int ) 

what need select, based on given thing id:

  • all records things has type = -1
  • all records things has type matching idchild idparent type of row matching given id.
  • if type of row matching given id -1 or doesn't exist in table relations (as idparent) need select records things

i having problem last scenario, tried joining relations table, can't come condition satisfy scenarios, suggestions?

update

this how now. need solve scenario given id not exists in table relations - need select records.

create table things (id int, type int) create table relations (id int, parent int, child int)  insert things values (1, 1) insert things values (2, -1) insert things values (3, 3) insert things values (4, 3) insert things values (5, 2) insert things values (6, -1)  insert relations values (1, 1, 2)  declare @id int = 1  select * things join relations r on r.parent = @id , type = r.child or type = -1 

so must solve situation @id = 2 example - need retrieve rows (same @id = 5, unless appears in relations in parent column somewhere).

update 2

i came that:

declare @id int = 2 declare @type int  select @type = type things id = @id  if @type > -1 begin select t.* things t join relations r on (r.parent = @id , t.type = r.child) or t.type = -1 end else begin select * things end 

i'm quite sure can done differently, without conditional if, optimized.

 things  left outer join relations     on relations.idparent = things.type  things.type = -1 or relations.idparent null  

Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -