Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Left Join Query 1

Status
Not open for further replies.

agp4

Programmer
Oct 7, 2005
10
0
0
GB
Hi,

I have the following 2 tables;

Table1: Products (ID, Customer, ProductName, Price)
Table2: Orders (ID, Customers, ProductName, Price, Quantity)

I want to create a query that selects all the records from the Products table and also any matching records from the Orders table for a given customer. However, if there is a match in the Orders table, then I want the value in the Orders table to supercede the value from the Products table.

i.e.

If CustomerA has the following 3 products in the Products table;

ProdA, £1.99
ProdB, £3.00
ProdC, £5.00

The orders table includes the following records for CustomerA

ProdA, £1.99, 15
ProdB, £3.99, 10


I now want to display a recordset from the above tables that looks like the following;

ProdA, £1.99, 15
ProdB, £3.99, 10
ProdC, £5.00, 15

Please note there was no record for ProdC in the Orders table, but this was still displayed and because there was a matching record for ProdB in the Orders table the price value was taken from the Orders table (£3.00 - £3.99).

I know I need a left join but can't get this to work!

Any help would be much appreciated!

Many Thanks,
AGP



 
I'm not clear on how you got 15 quantity for ProdC, since there wasn't a row in the orders table. Other than that, this should work
Code:
SELECT p.productName, COALESCE( o.price, p.price ) price, o.quantity
FROM  `products` p
LEFT JOIN  `orders` o ON p.customer = o.customer
AND p.productName = o.productName

-----------------------------------------
I cannot be bought. Find leasing information at
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top