Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Join Question

Tags:

sql

sql-server

I have an interesting question for an SQL Join. I have 2 tables, examples below:

Table1: ID (int), Value(string)
Table2: ID (int), ForeignID(int), (Value)

The field ForeignID in Table2 is the foreign key of the ID in Table1. For a given entry in Table1, I have multiple entries in Table2 as follows:

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

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

If I do an inner join such as

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

I would get

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

Is there a way to only get the TOP entry in Table2 such as:

Hello world, First entry  
Bonjour, Third entry  
like image 707
Steve Kiss Avatar asked Jul 26 '26 16:07

Steve Kiss


1 Answers

This works too:

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
like image 175
Tamila Avatar answered Jul 28 '26 07:07

Tamila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!