Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL one to many with inner join

Tags:

sql

join

Say I have two tables, table 1 and table 2. Table 1 has a one to many relationship with table 2.

If table 1 is my base table (SELECT something FROM table1) with an inner join to table 2, then what values from table two would be returned when selecting any fields from table 2?

  • The first value returned? As with excel's vlookup function?
  • The last value on the join?

E.G.

Table1
     Account ID |      email      
         1      |   [email protected]
         2      |   [email protected]
         3      |   [email protected]

Table 2
Subscription ID | Account ID  |       Email       |      Created
    100         |     1       |    [email protected]    |    2014-01-01
    102         |     2       |    [email protected]  |    2014-02-02
    103         |     1       |    [email protected]    |    2014-03-03

So if I ran a query to select the created date of an account based on subscriptions I could just run SELECT min(Created) to get the first one.

But what's the default behavior? If my left table is table 1 joined onto table 2 on account ID and I select created field, which will be returned? 2014-01-01 or 2014-03-03?

like image 263
Doug Fir Avatar asked Sep 23 '14 18:09

Doug Fir


People also ask

How will you handle one-to-many relationship in SQL JOIN?

In a one-to-many kind of relationship, one row of the first table can be related to multiple rows of the second table. In a relational database this can be implemented with the second table having a first_table_id column that says to which row of the first table that row is related.

What is a 1 to many join?

✓ One-to-many – Each row in one table is linked (or related) to one, or more, rows in another table using a “key” column. ✓ Many-to-many – One, or more, rows in one table is linked (or related) to one, or more, rows in another table using a. “key” column. The SQL Optimizer and Join Algorithms.

Is an inner join one to one?

Inner join: This join will return the data that has one-to-one mapping or matching records present in both the tables.

Does inner join return multiple matches?

An inner join returns all rows from x with matching values in y, and all columns from both x and y. If there are multiple matches between x and y, all match combinations are returned.


1 Answers

You would return both records. When you JOIN tables, you get all the records that meet the criteria of the JOIN and the WHERE clauses and any GROUP BY / HAVING clauses. If you want only one returned, you have to write the code to specify which one you want.

like image 60
HLGEM Avatar answered Oct 22 '22 12:10

HLGEM