Select 主 table 的记录基于第 4 个详细信息 table 的条件
Select records from master table based on condition from 4th detail table
我有 4 个表:表 1、表 2、表 3、表 4 每个表都是前一个表的详细信息,例如表 4 是表 3 的详细信息,依此类推。这是我的架构:
表 1:
PK1 Integer,
Name1 varchar(15),...
表 2:
PK2 Integer,
PK1 Integer, -- This is foreign key to Table1.PK1
Name2 varchar(15),...
表 3:
PK3 Integer,
PK2 Integer, -- This is foreign key to Table2.PK2
Name3 varchar(15),...
表 4:
PK4 Integer,
PK3 Integer, -- This is foreign key to Table3.PK3
Name4 varchar(15),...
我现在需要根据 Table4 中的特定值 select Table1 中的记录,例如当 Table4.PK4 = 3 时。
所以我这样试过:
Select * from table1 where PK1 in (
select PK1 from Table2 where PK2 in (
select PK2 from Table3 where PK3 in (
select PK3 from Table4 where PK4 = 3
)))
我得到了正确的结果,但这是 best/optimized 方式还是我应该使用更好的 SQL 方式?
为什么不使用所有联接:
Select DISTINCT table1.*
from table1
INNER JOIN table2 ON table1.PK1 = table2.PK1
INNER JOIN table3 ON table2.PK2 = table3.PK2
INNER JOIN table4 ON table3.PK3 = table4.PK3
WHERE table4.PK4 = 3
我认为查询引擎应该足够智能来优化您的查询,但至少从可读性的角度来看,我上面提供的那个更具可读性
我认为这会比其他答案更有效。
您首先进行连接,这可能无关紧要,因为我很确定他的表没有那么大。但是对于大数据,我认为最好将 where 子句放在 join
的 ON 条件中
Select DISTINCT table1.*
from table4
INNER JOIN table3 ON (table4.PK3 = table3.PK3 AND table4.PK4=3)
INNER JOIN table2 ON table2.PK2 = table3.PK2
INNER JOIN table1 ON table2.PK1 = table1.PK1
我有 4 个表:表 1、表 2、表 3、表 4 每个表都是前一个表的详细信息,例如表 4 是表 3 的详细信息,依此类推。这是我的架构:
表 1:
PK1 Integer,
Name1 varchar(15),...
表 2:
PK2 Integer,
PK1 Integer, -- This is foreign key to Table1.PK1
Name2 varchar(15),...
表 3:
PK3 Integer,
PK2 Integer, -- This is foreign key to Table2.PK2
Name3 varchar(15),...
表 4:
PK4 Integer,
PK3 Integer, -- This is foreign key to Table3.PK3
Name4 varchar(15),...
我现在需要根据 Table4 中的特定值 select Table1 中的记录,例如当 Table4.PK4 = 3 时。
所以我这样试过:
Select * from table1 where PK1 in (
select PK1 from Table2 where PK2 in (
select PK2 from Table3 where PK3 in (
select PK3 from Table4 where PK4 = 3
)))
我得到了正确的结果,但这是 best/optimized 方式还是我应该使用更好的 SQL 方式?
为什么不使用所有联接:
Select DISTINCT table1.*
from table1
INNER JOIN table2 ON table1.PK1 = table2.PK1
INNER JOIN table3 ON table2.PK2 = table3.PK2
INNER JOIN table4 ON table3.PK3 = table4.PK3
WHERE table4.PK4 = 3
我认为查询引擎应该足够智能来优化您的查询,但至少从可读性的角度来看,我上面提供的那个更具可读性
我认为这会比其他答案更有效。 您首先进行连接,这可能无关紧要,因为我很确定他的表没有那么大。但是对于大数据,我认为最好将 where 子句放在 join
的 ON 条件中Select DISTINCT table1.*
from table4
INNER JOIN table3 ON (table4.PK3 = table3.PK3 AND table4.PK4=3)
INNER JOIN table2 ON table2.PK2 = table3.PK2
INNER JOIN table1 ON table2.PK1 = table1.PK1