问题
The exact query:
SELECT
coupon_coupons.code,coupon_coupons.discountTypeAS 'type',coupon_coupons.discountAmountAS 'amount',coupon_coupons.discountAppliedAS 'applied',coupon_coupons.description,
group_concat(coupon_targetsku.skuseparator ';') AS 'targetsku'
FROMcoupon_coupons
LEFT JOINcoupon_targetskuONcoupon_coupons.code=coupon_targetsku.code
WHEREcoupon_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
Thanks in advance.
回答1:
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
回答2:
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)
来源:https://stackoverflow.com/questions/3974055/query-is-resulting-in-1-row-with-null-values-when-id-is-not-found