Page 1 of 1

SQL problem

Posted: 27 Jul 2005, 14:36
by the-happening
Not knowing a gret deal about SQL could someone help with the following question:

I need to do a join on two tables what would be the SQL syntax for that?

It is for a friend so if the above statement makes no sense i apologise.

Thanks in advance.

Posted: 27 Jul 2005, 14:41
by Quiff Boy
inner, left or right join? :D :lol:

this is a fairly good description of what they each do:

http://www.w3schools.com/sql/sql_join.asp

Code: Select all

Using Joins
OR we can select data from two tables with the JOIN keyword, like this:

Example INNER JOIN
Syntax

SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield 

Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID 

The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Employees that do not have matches in Orders, those rows will not be listed.

Result

Name Product 
Hansen, Ola Printer 
Svendson, Stephen Table 
Svendson, Stephen Chair 

Example LEFT JOIN
Syntax

SELECT field1, field2, field3
FROM first_table
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield 

List all employees, and their orders - if any.

SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID 

The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table (Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed.

Result

Name Product 
Hansen, Ola Printer 
Svendson, Tove   
Svendson, Stephen Table 
Svendson, Stephen Chair 
Pettersen, Kari   

Example RIGHT JOIN
Syntax

SELECT field1, field2, field3
FROM first_table
RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield 

List all orders, and who has ordered - if any.

SELECT Employees.Name, Orders.Product
FROM Employees
RIGHT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID 

The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no matches in the first table (Employees). If there had been any rows in Orders that did not have matches in Employees, those rows also would have been listed.

Result

Name Product 
Hansen, Ola Printer 
Svendson, Stephen Table 
Svendson, Stephen Chair 

Example
Who ordered a printer?

SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer' 

Result

Name 
Hansen, Ola 
good luck :lol: :D

Posted: 27 Jul 2005, 23:54
by Francis
I do this for a living and I haven't got a clue what that means. :eek:

Oracle developers do it on tables.