2016-02-19 59 views
0

我有一個表coupons和另一個表coupon_usescoupons有一個整數屬性,限制可以使用優惠券的次數。每次使用優惠券時,都會創建一個coupon_uses記錄。如何在另一個表中按組計數過濾一個表

------------ --------------- 
| coupons | | coupon_uses | 
|----------| |-------------| 
| id  | | coupon_id | 
| code  | | ...   | 
| max_uses | --------------- 
----------- 

我該如何構建一個查詢,從而可以基於特定優惠券有多少對應的coupon_uses來過濾優惠券表?例如,我希望使用的所有優惠券的使用次數少於它們的max_uses屬性允許的次數。

+0

你能告訴我們你迄今爲止做了什麼? – GabrielVa

回答

1
--- The coupons which are already used to its max limit 
SELECT count(cu.*), cp.id, cp.max_uses 
FROM coupons cp 
LEFT JOIN coupon_uses cu ON cp.id = cu.coupon_id 
GROUP BY cp.id, cp.max_uses 
HAVING count(cu.*) = cp.max_uses 

-- The coupons which are remaining 
SELECT count(cu.*), cp.id, cp.max_uses , cp.max_uses - count(cu.*) AS remaing_usage 
FROM coupons cp 
LEFT JOIN coupon_uses cu ON cp.id = cu.coupon_id 
GROUP BY cp.id, cp.max_uses 
HAVING count(cu.*) < cp.max_uses 
1

這應該會給你你要找的東西;

SELECT c.max_uses , 
    c.id , 
    c.code , 
    COUNT(coupon_id) AS 'uses' 
FROM coupon_uses cu 
    LEFT JOIN coupons c ON c.ID = cu.ID 
GROUP BY c.max_uses , 
    c.id , 
    c.code  
    Having c.max_uses > count(coupon_id) 
0

有0用途將得到計數1中左側的優惠券加盟。 因此,我使用UNION來計算使用的優惠券,而不是單獨使用。

SELECT cp.code, count(*) uses 
FROM coupons cp 
JOIN coupon_uses cu ON CP.id = cu.coupon_Id 
GROUP BY cp.id, cp.code 
HAVING count(*) < cp.max_uses 
UNION 
SELECT cp.code, 0 uses 
FROM coupons cp 
LEFT JOIN coupon_uses cu ON CP.id = cu.coupon_Id 
WHERE cu.coupon_Id IS NULL 
相關問題