Query is resulting in 1 row with null values when id is not found

旧时模样 提交于 2020-01-02 05:29:08

问题


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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!