1
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查询?我可以做的更好