2013-03-20 44 views
1

现状:选择所有记录,如果加入id为null

Table1: id, 
Table2: id, table1_id 
Table3: id, table2_id 
user: id, table1_id (can be null), table2_id(can be null), table3_id(can be null) 

表1,表2,表3形式的分层结构(单表1排尊者许多行表2中,对于单个表2排有许多行表3)

我需要从表3中选择记录分配给选定的用户。 已分配意味着用户记录匹配中的ID (table1_id = Table1.id AND table2_id = Table2.id AND table3_id = Table3.id) 但是,如果用户记录中的值为空,则表示该用户已分配给相应表中的所有记录。

if table1_id = null query should return all rows 
elif table2_id = null query should return all rows where (table1_id = Table1.id) 
elif table3_id = null query should return all rows where (table1_id = Table1.id AND table2_id = Table2.id 
elif query should return all rows where (table1_id = Table1.id AND table2_id = Table2.id AND table3_id = Table3.id) 

我的命题:

declare @table1_id int 
declare @table2_id int 
declare @table3_id int 

select @table1_id = table1_id, @table2_id = @table2_id, @table3_id = @table3_id 
from user where id = 5 (5 is parmeter) 

select * from Table3 where 
(@table1_id IS NULL OR @table1_id = 
     (select table1_id from Table2 where Table2.id = Table3.table2_id)) AND 
(@table2_id IS NULL OR @table2_id = Table3.table2_id) AND 
(@table3_id IS NULL OR @table3_id = Table3.id) 

是好SQL查询?我可以做的更好

回答

1

你可以把所有这一切到一个查询:

select table3.* 
from table3 cross join 
    (select table1_id, table2_id, table3_id 
     from user 
     where id = 5 
    ) const 
where (const.table1_id is null or const.table1_id in (select table1_id from table2 where table2.id = table3.table2_id)) and 
     (const.table2_id is null or const.table2_id = table3.table2_id) and 
     (const.table3_id is null or const.table3_id = table3.id) 

in取代=,因为你可以有从子选择多的回报。

还有其他方式可以使用显式连接来表达这一点。但是,它们可能会导致重复行,具体取决于表之间的关系。