views:

28

answers:

2

The exact query:

SELECT coupon_coupons.code,
coupon_coupons.discountType AS 'type',
coupon_coupons.discountAmount AS 'amount',
coupon_coupons.discountApplied AS 'applied',
coupon_coupons.description,
group_concat(coupon_targetsku.sku separator ';') AS 'targetsku'
FROM coupon_coupons
LEFT JOIN coupon_targetsku ON coupon_coupons.code = coupon_targetsku.code
WHERE coupon_coupons.code = 'testCode'

coupon_coupons.code = primary key
coupon_targetsku.code = fk(coupon_coupons.code)

If the coupon_coupons.code is found in the database the query operates as expected, but when its not found the result set that is returned is one row with all NULL values. I'm guessing its something I'm doing wrong with the left join.

I would like this query to return zero rows if the code is not found.

I'm using mysql:
Server version 5.1.36-community-log
Protocol version: 10

This is my first time asking a question here please let me know if there is any other information i should be providing.

Thanks in advance.

A: 

The LEFT JOIN keyword returns all rows from the left table (coupon_coupons), even if there are no matches in the right table (coupon_targetsku).

For your situation a JOIN is what you want (Returns rows when there is at least one match in both tables)

nathan-unleashed
Using simply the JOIN statement resulted in the same results.
Steven Zurek
oh, try taking out the group_concat. It is likely returning rows due to the concat returning a blank string. possibly replace with: group_concat(COALESCE(coupon_targetsku.sku, "") separator ';') AS 'targetsku'
nathan-unleashed
A: 

It's good to use group by when using group_concat()

SELECT coupon_coupons.code,
coupon_coupons.discountType AS 'type',
coupon_coupons.discountAmount AS 'amount',
coupon_coupons.discountApplied AS 'applied',
coupon_coupons.description,
group_concat(coupon_targetsku.sku separator ';') AS 'targetsku' 
FROM coupon_coupons
JOIN coupon_targetsku ON coupon_coupons.code = coupon_targetsku.code 
WHERE coupon_coupons.code = 'testCode'
GROUP BY coupon_coupons.code
Derek Adair