SQL加入问题

时间:2011-08-30 02:16:50

标签: sql sql-server

我对SQL Join有一个有趣的问题。我有2个表,下面的例子:

表1:ID(int),值(字符串)
表2:ID(int),ForeignID(int),(Value)

Table2中的字段ForeignID是Table1中ID的外键。对于表1中的给定条目,我在表2中有多个条目,如下所示:

Table1:  
ID, Value  
0, "Hello World"  
1, "Bonjour"  

Table2:  
ID, ForeignID, Value  
0, 0, "First entry"  
1, 0, "Second entry"  
2, 1, "Third entry"  

如果我进行内部联接,例如

SELECT Table1.Value, Table2. Value FROM 
Table1 INNER JOIN Table2 ON Table1.ID = Table2.ForeignID

我会得到

Hello world, First entry  
Hello world, Second entry  
Bonjour, Third entry  

有没有办法只获得Table2中的TOP条目,例如:

Hello world, First entry  
Bonjour, Third entry  

6 个答案:

答案 0 :(得分:5)

这也有效:

SELECT  Table1.value
        , Table2.value
FROM    Table1 
        INNER JOIN Table2 ON Table1.id = Table2.foreignID
        INNER JOIN (   
          SELECT    MIN(ID) AS ID, ForeignID
          FROM      Table2
          GROUP BY  ForeignID
        ) MinID ON Table2.foreignid = MinID.foreignid
                   AND Table2.id = MinID.id

答案 1 :(得分:2)

SELECT Table1.Value, 
       (SELECT TOP 1 Table2.Value 
          FROM Table2 
         WHERE Table2.ForeignID = Table1.ID) 
FROM Table1 

答案 2 :(得分:2)

SELECT 
t1.Value, 
(  
    SELECT TOP 1 t2.Value FROM Table2 t2
    WHERE t2.ForeignID = t1.ID
    ORDER BY t2.ID ASC
) 
FROM Table1 t1

答案 3 :(得分:1)

由于您标记了SQL,因此这里是ANSI SQL查询(应该适用于SQL Server 2005+):

WITH TT (ID, ForeignID, Value, N) AS (
    SELECT ID, ForeignID, Value,
           ROW_NUMBER() OVER(PARTITION BY ForeignID ORDER BY ID)
      FROM Table2
)
    SELECT T1.Value, T2.Value
      FROM Table1 T1
INNER JOIN TT T2
        ON T1.ID = T2.ForeignID
       AND T2.N = 1;

它使用公用表表达式和窗口函数。

答案 4 :(得分:0)

这是另一个变体,它确保table2在正确的键上连接到table1。

SELECT t1.Value,  
       t2.Value
  FROM Table1 t1 
       INNER JOIN Table2 t2 
       ON t2.ForeignID = (SELECT MIN(sub.ForeignID) 
                          FROM Table2 sub WHERE sub.ForeignID = t1.ID) 

答案 5 :(得分:0)

编辑,实际上,抓住它。 Tamila的回答对我来说更好。

如果你可以在你的table2中添加一个boolean is_first标志,那么事情变得容易多了,这将为你完成这项任务:

SELECT table1."value", table2."value" 
FROM table1 
INNER JOIN table2 ON table1.id = table2.foreign_id
WHERE table2.is_first = true

我不知道Daniel的,cgatian或Leons的答案是否适用于您的数据库。我在Postgres上,它对我不起作用。