I’ve got a query to find abandoned carts that looks like this:
SELECT c.customerid,
c.custconfirstname,
c.custconemail,
o.ordstatus,
o.orddate,
GROUP_CONCAT( 'Order Id: ', orderid, ' | Product name: ', ordprodname, ' | Quantity: ', ordprodqty, '<br>' ) AS ordered_items
FROM isc_customers c
LEFT OUTER JOIN isc_orders o ON o.ordcustid = c.customerid
LEFT OUTER JOIN isc_order_products op ON op.orderorderid = o.orderid
LEFT OUTER JOIN isc_product_images pi ON pi.imageprodid = op.orderprodid
GROUP BY c.customerid
HAVING COUNT( DISTINCT o.ordcustid ) >0
AND o.ordstatus = 0
AND o.orddate < UNIX_TIMESTAMP( ) - '18000'
AND o.orddate > UNIX_TIMESTAMP( ) - '259200'
For each customer (unique customerid) The BLOB will produce something like this for ordered_items:
Order Id: 15256 | Product name: PROD A | Quantity: 1
,Order Id: 15256 | Product name: PROD B | Quantity: 1
,Order Id: 15299 | Product name: PROD A | Quantity: 1
,Order Id: 15301 | Product name: PROD A | Quantity: 1
This can basically be interpreted that the customer has had 3 abandoned carts in the time frame. Because this query will be used to send out an abandoned cart email I don’t want to spam and send an email with every product from every abandoned cart (the unique orderid) for various reasons, including that in the example above the customer has tried to put Product A in the cart 3 times over 3 orders and thus would get the item 3 times on the email.
So how can I limit the query so that it will only return the results of 1 orderid per customerid?
Add DISTINCT in your query and that will make it.
http://www.w3schools.com/sql/sql_distinct.asp