SQL从一个表中获取特定列,并在一个查询中从连接表中获取所有行

时间:2010-10-19 14:06:35

标签: subquery join sql

之前可能已经提出这个问题而我找不到它。

我在数据库中的几个表上有一对多的关系。

  • 表1
  • table2
  • 表3

table2 - table3是1-many关系

这是对我所拥有的模仿:

select
table1.id
table1.Column
table2.Column2
-- I want all entries here from table 3 here as well
From table1 t1
left outer join table2 t2 on t2.ID = t1.ID
left outer join join table3 t3 on t3.ID2 = t2.ID2

是否可以在select查询中指定属于table3的所有条目而不在select语句中指定子查询?

另外,这看起来不错吗?正如我在过去所说的那样,我对SQL非常陌生,因此我的代码很糟糕......

编辑

对不起,我猜错了。我需要每个应该在table3

中的每一行的列
select
table1.id,
table1.Column,
table2.Column2,
-- I'm going to need a subquery here aren't I...?
table3.columnFromRrow1,
table3.columnFromRrow2,
table3.columnFromRrow3
From table1 t1
left outer join table2 t2 on t2.ID = t1.ID
left outer join join table3 t3 on t3.ID2 = t2.ID2

3 个答案:

答案 0 :(得分:2)

;WITH cte AS
     ( SELECT table1.t1id,
              table1.t1col,
              table2.t2col,
              table3.t3col,
              ROW_NUMBER() OVER (PARTITION BY t1id,t1col,t2col 
                                 ORDER BY table3.id) AS RN
     FROM     table1 t1
              LEFT OUTER JOIN table2 t2
              ON       t2.ID = t1.ID
              LEFT OUTER JOIN
              JOIN table3 t3
              ON       t3.ID2 = t2.ID2
     )
SELECT 
   t1id,
   t1col,
   t2col,
   MAX(CASE WHEN RN=1 THEN t3col END) AS columnFromRrow1,
   MAX(CASE WHEN RN=2 THEN t3col END) AS columnFromRrow2,
   MAX(CASE WHEN RN=3 THEN t3col END) AS columnFromRrow3
FROM cte
WHERE RN<=3
GROUP BY t1id,t1col,t2col

答案 1 :(得分:1)

我已修改(并更正了您的查询以执行您想要的操作)。

SELECT 
  table1.id,
  table1.Column,
  table2.Column2, 
  table3.* -- All columns from table3
FROM table1 AS t1 
     LEFT OUTER JOIN table2 AS t2 
       ON t2.ID = t1.ID 
     LEFT OUTER JOIN table3 AS t3 
       ON t3.ID2 = t2.ID2 

注意:此答案不再有效,因为原始问题已被修改...

答案 2 :(得分:-1)

使用*

select
table1.id
table1.Column
table2.Column2
-- I want all entries here from table 3 here as well
table3.*
From table1 t1
left outer join table2 t2 on t2.ID = t1.ID
left outer join join table3 t3 on t3.ID2 = t2.ID2