Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Joins . One to many relationship

Tags:

sql

sql-server

I have two tables as below

Table 1
-----------------------------------
UserID   | UserName | Age | Salary
-----------------------------------
1        | foo      | 22  | 33000       
-----------------------------------
Table 2
------------------------------------------------
UserID   | Age      | Salary     | CreatedDate
------------------------------------------------
1        | NULL     | 35000      | 2015-01-01
------------------------------------------------
1        |  28      | NULL       | 2015-02-01
------------------------------------------------
1        |  NULL    | 28000      | 2015-03-01
------------------------------------------------

I need the result like this.

Result
-----------------------------------
UserID   | UserName | Age | Salary
-----------------------------------
1        | foo      | 28  | 28000
-----------------------------------

This is just an example. In my real project I have around 6 columns like Age and Salary in above tables.

In table 2 , each record will have only have one value i.e if Age has value then Salary will be NULL and viceversa.

UPDATE :

Table 2 has CreatedDate Column. So i want to get latest "NOTNULL" CELL Value instead of maximum value.

like image 377
J Santosh Avatar asked Aug 17 '15 06:08

J Santosh


People also ask

What join to use one-to-many?

The table on the "one" side of the "one-to-many" relationship should have a primary key column. The other table should have a foreign-key defined pointing to the primary key on the first table. To return results from both tables you'd add an INNER JOIN clause to join both tables.

IS LEFT join 1 to many?

SQL LEFT JOIN examples Each location belongs to one and only one country while each country can have zero or more locations. The relationship between the countries and locations tables is one-to-many.

What are the 4 types of JOINs in SQL?

Four types of joins: left, right, inner, and outer.

How do you determine if a relationship is one-to-many?

A one-to-many relationship is created if only one of the related columns is a primary key or has a unique constraint. In the relationship window in Access, the primary key side of a one-to-many relationship is denoted by a number 1. The foreign key side of a relationship is denoted by an infinity symbol.


1 Answers

You can get this done using a simple MAX() and GROUP BY:

select t1.userid,t1.username, MAX(t2.Age) as Age, MAX(t2.Salary) as Salary
from table1 t1 join
     table2 t2 on t1.userid=t2.userid
group by t1.userid,t1.username

Result:

userid  username    Age   Salary
--------------------------------
1       foo         28    35000

Sample result in SQL Fiddle

like image 109
Raging Bull Avatar answered Oct 05 '22 00:10

Raging Bull