Module 3 - Multiple relation SQL queries

Renaming

  1. Qualifying attribute names
  2. Declaring an alias

alt text

Cartesian Product

Also known as a CROSS JOIN

alt text

Joins

Example

A few weeks ago we had an Example ER model like this:

Focus on EMPLOYEE and DEPARTMENT, and the MANAGES relationship

alt text

There two relationships were mapped as such:

I know:

How can I connect both of these relations (tables) into one long table so that I can see the department and its respective Employee?

Equi-joins in SQL - Examples

-- Equi-join using WHERE
SELECT E.name, D.dName
FROM Department AS D, Employee AS E
WHERE D.mgrSSN = E.ssn;

-- Equi-join using JOIN
SELECT E.name, D.dName
FROM  Department AS D
JOIN Employee AS E ON  D.mgrSSN = E.ssn

Theta join

θ{=,,<,>,,} \theta \in \{ =, \ne, <, >, \ge, \le \}


INNER and OUTER joins

alt text

MYSQL does not support FULL OUTER JOIN operations. How would we achieve the same result without the operation?

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id

Set operations

alt text

Use of ALL

Each automatically eliminates duplicates;

UNION

SELECT  starID
FROM  Movie M
JOIN StarsIn S 
ON M.movieID = S.movieID
WHERE year = 1944
UNION
SELECT  starID
FROM  Movie M
JOIN StarsIn S 
ON M.movieID = S.movieID
WHERE year = 1974

INTERSECTION

Example: Find IDs of MovieStars who’ve been in a movie in 1944 and 1974.

SELECT  starID
FROM  Movie M
JOIN StarsIn S 
ON M.movieID = S.movieID
WHERE year = 1944
INTERSECT
SELECT  starID
FROM  Movie M
JOIN StarsIn S 
ON M.movieID = S.movieID
WHERE year = 1974

Difference - EXCEPT/MINUS

Example: Find IDs of stars who have been in a movie in 1944 but not in 1974.

SELECT   starID
FROM     Movie M
JOIN StarsIn S ON M.movieID = S.movieID
WHERE year = 1944
EXCEPT
SELECT   starID
FROM     Movie M
JOIN StarsIn S ON M.movieID = S.movieID
WHERE year = 1974