【问题标题】:Unable to form a single query to join multiple tables无法形成单个查询来连接多个表
【发布时间】:2021-02-11 14:56:14
【问题描述】:

我必须编写一个选择查询来从七个表中获取所有详细信息。早些时候我有单独的查询,但现在我正在优化查询。 以下是我的表结构:

Main Table (SN, model , regId) -- 1 row
Table1(col1,col2....SN)  - SN is forienKey  -- 1 row
Table2(col1,col2,....SN) -  SN is forienKey   -- 1 row
Table3(col1,col2,.....regId) - regId is forienKey  -- 1 row
Table4(col1,col2,.....regId) - regId is forienKey - 2 rows
Table5(col1,col2,.....regId) - regId is forienKey - 2 rows
Table6(col1,col2,.....regId) - regId is forienKey  - 1 row

main tabletable 4table 5 之间有一个one to many mapping

我尝试使用内部连接来获取行,但我得到了重复的值。下面是我写的查询。我有什么遗漏吗?

select * from MainTable 
   inner join Table1 on MainTable.SN = Table1.SN
   inner join Table2 on MainTable.SN = Table2.SN
   inner join Table3 on MainTable.regId = TABLE3.regId
   inner join TABLE4 on MainTable.regId = Table4.regId
   inner join TABLE5 on MainTable.regId = Table5.regId
   inner join TABLE6 on MainTable.regId = Table6.regId

【问题讨论】:

  • 为什么要混合使用 JOIN USING 和 WHERE 子句连接条件?非常混乱。
  • 表之间是一对多的关系,你要求我们把它变成一对一的关系;你认为我们如何做到这一点,我们不知道你的数据。您要显示多行中的哪一行?还是要聚合多行?

标签: java sql inner-join


【解决方案1】:

尝试像下面这样连接表格以将所有表格连接在一起

  select * from (select * from MainTable 
        inner join Table1 on MainTable.SN = Table1.SN
        inner join Table2 on Table1.SN = Table2.SN ) tempMain 
   inner join Table3 on tempMain.regId = TABLE3.regId
   inner join TABLE4 on TABLE3.regId = Table4.regId
   inner join TABLE5 on Table4.regId = Table5.regId
   inner join TABLE6 on Table5.regId = Table6.regId

虽然从您的示例中我不知道表 2 和表 3 是否相关。无论如何,您可以尝试找到类似的。

【讨论】:

  • table2和table 3没有关系
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多