情况:
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多行)
我需要从分配给选定用户的 Table3 中选择记录。已分配表示用户记录中的 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查询吗?我能做得更好吗