-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5.SQL Joins.sql
More file actions
72 lines (54 loc) · 1.9 KB
/
Copy path5.SQL Joins.sql
File metadata and controls
72 lines (54 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use ecom;
-- What are joins?
-- Simply put, joins are used in SQL when we want to join multiple tables into one.
create table price(
order_id int,
cust_id int,
price float
);
insert into price values (1,101,1000),(2,201,1100),(3,501,1200);
create table customer(
id int,
name varchar(40),
email varchar(50)
);
insert into customer values (101,'athira','aa'),(201,'aswathi','bb'),(301,'anuvind','cc');
select * from price;
select * from customer;
-- Inorder to apply join, we need a joining key. Here, cust_id from price table and id from customer table.
-- Types of join
-- INNER JOIN : Intersection. ie, record should be available in both the tables.
select id, order_id, price, name, email -- for same column names use tablename.columnname
from price
inner join customer
on price.cust_id = customer.id;
select p.*,c.name
from price p -- We can use alias for table names as well to make query simple.
inner join customer c
on p.cust_id = c.id;
select *
from price p
join customer c -- By default, join is inner join
on p.cust_id = c.id;
-- LEFT JOIN : All the records from left table no matter weather record is available in both the tables or not.
select *
from price
left join customer
on cust_id = id; -- The extra record in left table will be filled with null values for columns in right table.
-- RIGHT JOIN : All the records from right table no matter weather record is available in both the tables or not.
select *
from price
right join customer
on cust_id = id; -- The extra record in right table will be filled with null values for columns in left table.
-- FULL JOIN : All the records from both table will be present. MySQL does not support FULL OUTER JOIN, we use a UNION on LEFT and RIGHT join
select *
from price p
left join customer c
on p.cust_id = c.id
union
select *
from price
right join customer
on cust_id = id;
drop table price;
drop table customer;