Please help me to write a SQL query to extract unique orders from below tables. To do that I Have prepared a SQL query. It’s working fine but in some place its returning some duplicate rows as some orders have more than one products.
For Example:
Customer can buy “IPAD” in one order. However, if they purchase “Ipad” and “Android” as bundle they will receive 50% discount and they can save money. In this case, we will get two products under 1 order. However, customer will pay as one product(i.e $120). To allocate order properly, we have created an extra row for the extra product(if products two). If bundle contain three products, it will create three rows in “product_orders” table respectively.
Example “product_orders” table for multiple products:
id orders_id product_id qty
1 3 2 1
2 2 1 1
3 3 3 1
Please check above example table, one order_id copied twice for the bundle order.
If we able to extract one order information, we will get the whole bundle information. So, we don’t need the extra row.
The Query I have applied:
Select
orders.id,
orders.order_price,
orders.purchase_date,
customers.email,
product_orders.qty,
products.name
from
orders
INNER JOIN product_orders on orders.id=product_orders.orders_id
INNER JOIN products on product_orders.product_id=products._id
INNER JOIN customers on orders.customer_id =customers.id
Result of the above query:**
Id order_price purchase_date email qty name
3 20 12/6/2011 aa@gmail.com 1 Ipad
3 20 12/6/2011 aa@gmail.com 1 Android
1 40 10/5/2011 bb@gmail.com 2 Laser hair remover
Required Result:
remove duplicate order ID
Id order_price purchase_date email qty name
3 20 12/6/2011 aa@gmail.com 1 Ipad
1 40 10/5/2011 bb@gmail.com 2 Laser hair remover
Table 1: orders
id customer_id order_price purchase_date
1 1 0.20 12/6/2011
2 2 0.20 12/6/2011
3 1 0.20 12/6/2011
4 1 0.20 12/6/2011
5 1 0.20 12/7/2011
6 3 199.00 12/7/2011
7 4 199.00 12/7/2011
8 5 199.00 12/7/2011
9 6 199.00 12/7/2011
10 7 199.00 12/7/2011
Table 2 : customers
id email name
1 aa@dealboard.com.au aa
2 bb@dealboard.com.au bb
3 cc@live.com.au cc
4 dd@acgglobal.com dd
5 ee.heinrich@det.nsw.edu.au ee
6 ff@optusnet.com.au ff
7 ssy@hotmail.com ss
table 3: products
id name
1 A Home Portable Laser Hair Remover
2 Ipad
3 android
4 Asus
5 s
6 10 inch Android
7 A Fabric Steamer Cleaner
8 A Magnetic Fly Screen Door
9 pillopw
10 LCD
table 4: product_orders
id orders_id product_id qty
1 1 1 1
2 3 3 1
3 3 4 1
4 4 1 1
5 4 2 1
6 6 1 1
7 7 1 1
8 4 2 1
9 4 3 1
10 10 1 1
Please help me to extract only 1 order from “product_orders” table and the query will omit other extra rows
Add extra
subquerywhich gets only one product perorder_idSQLFiddle Demo