0

我有三个表 Table1、Table2 和 Table3。

表 1 与表 2 具有一对多关系。表 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

4 回答 4

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;
于 2013-01-12T07:32:48.220 回答
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 小提琴演示

这会给你:

| T1KEY | T2KEY | T3KEY |
-------------------------
|     a |     c |     e |
|     a |     d |     h |
|     b |     x |     m |
|     b |     y |     p |
于 2013-01-12T06:14:01.970 回答
0

您需要先使用GROUP BY子句并使用MIN()for

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;

看到这个 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 |

演示

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

演示

于 2013-01-12T06:16:34.353 回答
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
于 2013-01-12T06:43:22.353 回答