状況:
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)
Table1、Table2、Table3 は階層構造を形成します (単一の table1 行の場合、Table2 に多くの行があり、単一の Table2 行の場合、Table3 に多くの行があります)。
選択したユーザーに割り当てられた Table3 からレコードを選択する必要があります。割り当て済みとは、ユーザー レコードの ID が一致する
(table1_id = Table1.id AND table2_id = Table2.id AND table3_id = Table3.id)
ことを意味します。ただし、ユーザー レコードの値が null の場合、対応するテーブルのすべてのレコードにユーザーが割り当てられていることを意味します。
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クエリですか?もっと上手にできますか