Week-5-2-SQL-ALIAS-JOIN

advertisement
Database
Week 5
SQL basics
JOIN, ALIAS
Fox MIS
Spring 2011
JOIN
• SQL joins are used to query data from two or more
tables, based on a relationship between certain
columns in these tables.
• JOIN(or INNER JOIN): Return rows when there is at
least one match in both tables
• LEFT JOIN: Return all rows from the left table, even
if there are no matches in the right table
• RIGHT JOIN: Return all rows from the right table,
even if there are no matches in the left table
• FULL JOIN: Return rows when there is a match in
one of the tables
INNER JOIN
P_Id
1
2
3
LastName
Hansen
Svendson
Pettersen
FirstName
Ola
Tove
Kari
Address
Timoteivn 10
Borgvn 23
Storgt 20
City
Sandnes
Sandnes
Stavanger
O_Id
1
2
3
4
5
OrderNo
77895
44678
22456
24562
34764
P_Id
3
3
1
1
15
•
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
•
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
•
JOIN(or INNER JOIN): Return rows when there is at least one match in both tables
P_Id
1
1
3
3
O_Id
3
4
1
2
LastName
Hansen
Hansen
Pettersen
Pettersen
FirstName
Ola
Ola
Kari
Kari
OrderNo
22456
24562
77895
44678
Non-standard, but Common syntax
• SELECT Persons.LastName, Persons.FirstName,
Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
• SELECT Persons.LastName, Persons.FirstName,
Orders.OrderNo
FROM Persons, Orders
WHERE Persons.P_Id=Orders.P_Id
• Above two will return the same results.
Example
• Database: Sakila, Table: Customer and
Customer_list
• Customer table manages customer’s first name
and last name in separate fields, while
customer_list table keeps them in one field.
• Task: Make the list of customer id, customer
name, their email addresses, and their active
statuses. Sort them by customer id.
ALIAS
• SELECT column_name(s)
FROM table_name AS alias_name
• SELECT column_name AS alias_name
FROM table_name
– You can give a table or a column another name by using an alias
• SELECT po.OrderID, p.LastName, p.FirstName
FROM Persons AS p, Product_Orders AS po
WHERE p.LastName='Hansen' AND p.FirstName='Ola‘
• SELECT Product_Orders.OrderID, Persons.LastName,
Persons.FirstName
FROM Persons, Product_Orders
WHERE Persons.LastName='Hansen' AND
Persons.FirstName='Ola'
Download