MySQL - JOINS

Table 1 - DEPT (Parent table)

DEPTNO DNAME LOC
1 TRN MUMBAI
2 EXP DELHI
3 MKTG PUNE

Table 2 - EMP (Child table)

EMPNO ENAME EMPSAL JOB DEPTNO MGR
1 ARUN 5000 M 1 4
2 AKASH 6000 C 1 1
3 KIRAN 7000 C 1 1
4 JACK 9000 M 2 NULL
5 THOMAS 8000 C 2 4

Joins

image.png

-- dept: driven table
-- emp: driving table
Select dname, ename from emp, dept
where dept.deptno = emp.deptno;

-- common column in both tables
-- tablename.columnname -> dept.deptno
-- tablename.columnname -> emp.deptno 

Note: Driving table is always less row than driven table for fast performance.

image.png

Note: outer loop must have less number of rows than inner loop.

1st time scan see deptno and scan in emp table
2nd time scan see deptno and scan in emp table
3rd time scan see deptno and scan in emp table
because dept table have 3 rows. 
Therefore 3 times full table scan.
DNAME ENAME
TRN ARUN
TRN AKASH
TRN KIRAN
EXP JACK
EXP THOMAS
-- Fast
-- dept: driving table, other loop, less rows
-- emp: driven table, inner loop, more rows
Select dname, ename from emp, dept
where dept.deptno = emp.deptno
order by 1;

-- Slow
-- emp: driving table, other loop, more rows
-- dept: driven table, inner loop, less rows
Select dname, ename from dept, emp
where emp.deptno = dept.deptno
order by 1;

Note: In order for join to work faster, preferably the driving table should be table with lesser number of rows.