选择性过滤三个表的连接

时间:2013-01-12 06:05:50

标签: sql

我有三个表Table1,Table2和Table3。

Table1与Table2有一对多的关系。表2与表3有一对多的关系。

假设table1有

-------------
t1key
-------------
a
b

Table2 has 
-------------
t1key | t2key
--------------
a        c
a        d
b        x
b        y


Table 3
------------
t2key | t3key
-------------
c      e
c      f
c      g
d      h
d      i
d      j
x      m
x      n
x      o
y      p
y      q
y      r

我希望连接三个表,以便它只返回table3中t2key的第一个唯一匹配

加入的结果应该是

a c  e
a d  h
b x  m
b y  p

目前我的应用程序会连接所有三个表,返回所有可能的行。我需要用上述条件对其进行过滤。

SELECT * FROM Table1 AS T1  
LEFT OUTER JOIN Table2 T2 ON T1.t1Key = T2.t1Key 
LEFT OUTER JOIN Table2 T3 ON T2.t2Key = T3.t2Key

4 个答案:

答案 0 :(得分:0)

像这样:

SELECT 
  t2.t1Key, 
  t2.t2key, 
  MIN(t3.t3key) t3key
FROM Table1 AS T1  
INNER JOIN Table2 T2 ON T1.t1Key = T2.t1Key 
INNER JOIN Table3 T3 ON T2.t2Key = T3.t2Key
GROUP BY t2.t1Key, 
         t2.t2key;

SQL Fiddle Demo

这会给你:

| T1KEY | T2KEY | T3KEY |
-------------------------
|     a |     c |     e |
|     a |     d |     h |
|     b |     x |     m |
|     b |     y |     p |

答案 1 :(得分:0)

您需要使用GROUP BY子句并使用MIN()作为第一个

SELECT t2.t1key, t2.t2key, MIN(t3.t3key) AS t3key
FROM Table1 AS T1  
LEFT JOIN Table2 T2 ON T1.t1Key = T2.t1Key 
LEFT JOIN Table3 T3 ON T2.t2Key = T3.t2Key
GROUP BY t2.t1Key, t2.t2key;

See this SQLFiddle

如果您只想显示每个表格中提供的数据,请使用INNER JOIN代替LEFT JOIN
例如假设Table2 'b', 'q'中有一行 然后,如果您使用LEFT JOIN,则会显示此结果

| T1KEY | T2KEY |  T3KEY |
--------------------------
|     a |     c |      e |
|     a |     d |      h |
|     b |     q | (null) | <-- It will show null value too
|     b |     x |      m |
|     b |     y |      p |

Demo

使用INNER JOIN它不会显示该记录

Demo

答案 2 :(得分:0)

DECLARE @table1 table
(
    t1 char(1)
)
INSERT INTO @table1
SELECT 'a' UNION ALL
SELECT 'b' 


DECLARE @table2 table
(
    t1 char(1),
    t2 char(1)
)
INSERT INTO @table2
SELECT 'a', 'c' UNION ALL
SELECT 'a', 'd' UNION ALL
SELECT 'b', 'x' UNION ALL
SELECT 'b', 'y' 

DECLARE @table3 table
(
    t1 char(1),
    t2 char(1)
)
INSERT INTO @table3
SELECT 'c', 'e' UNION ALL
SELECT 'c', 'f' UNION ALL
SELECT 'c', 'g' UNION ALL

SELECT 'd', 'h' UNION ALL
SELECT 'd', 'i' UNION ALL
SELECT 'd', 'j' UNION ALL

SELECT 'x', 'm' UNION ALL
SELECT 'x', 'n' UNION ALL
SELECT 'x', 'o' UNION ALL

SELECT 'y', 'p' UNION ALL
SELECT 'y', 'q' UNION ALL
SELECT 'y', 'r' 



SELECT 

    t1.t1,
    t2.t2,
    min(t3.t2)
FROM @table2 t2
INNER JOIN @table3 t3
ON t3.t1 = t2.t2
INNER JOIN @table1 t1
ON t1.t1 = t2.t1
GROUP BY t1.t1,
    t2.t2

答案 3 :(得分:0)

SELECT t1.t1key,t2.t2key,t3.t3key 
FROM Table1 t1  
INNER JOIN Table2 t2 ON t1.t1Key = t2.t1Key 
LEFT OUTER JOIN Table2 t3 ON t2.t2Key = t3.t2Key
group by t2.t1key,t2.t2key;