if else在mysql where子句中使用

时间:2017-12-29 14:29:56

标签: mysql sql left-join inner-join

我有内部联接的查询。目前,这会在product_id中存在coupon_restrict table时返回数据。 我想要做的是,如果product_id没有事件存在,那么它应该从优惠券表返回数据。

SELECT c.public_private, c.coupon_code, c.coupon_amount, c.coupon_type, 
c.coupon_zone_restriction, c.coupon_expire_date, c.is_stash
FROM coupons c, 
coupon_restrict cr, 
products p
WHERE 
c.coupon_type = 'P' 
AND (c.public = 1 OR c.public_private = 1) 
AND c.coupon_id = cr.coupon_id 
AND DATEDIFF(c.coupon_expire_date, NOW()) > 0
AND cr.product_id IN (1808)
AND cr.product_id = p.products_id
AND p.products_quantity > 0
AND cr.coupon_restrict = 'N'

1 个答案:

答案 0 :(得分:2)

如果您需要来自优惠券表的数据,无论他们的关联是否存在于其他表中,您还需要为coupon_restrictproducts留下联接

SELECT c.public_private, c.coupon_code, c.coupon_amount, c.coupon_type, 
c.coupon_zone_restriction, c.coupon_expire_date, c.is_stash
FROM coupons c
LEFT JOIN coupon_restrict cr ON c.coupon_id = cr.coupon_id  
                             AND cr.coupon_restrict = 'N'
                             AND cr.product_id IN (1808)
LEFT JOIN products p ON cr.product_id = p.products_id 
                     AND p.products_quantity > 0
WHERE c.coupon_type = 'P' 
AND (c.public = 1 OR c.public_private = 1) 
AND DATEDIFF(c.coupon_expire_date, NOW()) > 0

还要在on子句

中移动联接表的where过滤器