我的数据库中有这些结构:
Table coupon
coupon_id , code, max_used
Table coupon_history
coupon_history_id, coupon_id, used_date
我可以在“coupon.max_used”不超过“coupon_history”的总历史的情况下获取优惠券数据吗?我被困在这里。我需要一个优惠券代码。请帮我。
尝试使用JOIN
并IN
像这样:
SELECT cc.* FROM coupon cc
WHERE cc.coupon_id IN
(
SELECT c.coupon_id FROM Coupon c
LEFT JOIN
( SELECT coupon_id, COUNT(coupon_id) maxUsed
FROM coupon_history GROUP BY coupon_id
) ch
ON c.Coupon_id = ch.Coupon_id
WHERE c.max_used > ch.maxUsed
OR ch.maxUsed IS NULL
);
或者您可以JOIN
像这样简单地使用:
SELECT cc.* FROM coupon cc
JOIN
(
SELECT c.coupon_id FROM Coupon c
LEFT JOIN
( SELECT coupon_id, COUNT(coupon_id) maxUsed
FROM coupon_history GROUP BY coupon_id
) ch
ON c.Coupon_id = ch.Coupon_id
WHERE c.max_used > ch.maxUsed
OR ch.maxUsed IS NULL
) c ON cc.coupon_id = c.coupon_id;
编辑:关于你的第二个要求
试试这个查询:
SELECT cc.*,c.TotalUsed FROM coupon cc
JOIN
(
SELECT c.coupon_id,TotalUsed FROM Coupon c
LEFT JOIN
( SELECT coupon_id, COUNT(coupon_id) TotalUsed
FROM coupon_history GROUP BY coupon_id
) ch
ON c.Coupon_id = ch.Coupon_id
WHERE c.max_used > ch.TotalUsed
OR ch.TotalUsed IS NULL
) c ON cc.coupon_id = c.coupon_id;
你可以试试下面:
select IF(count(*)<max_used,'less','more') as T,coupon.*
from coupon
LEFT JOIN coupon_history ON coupon_history.coupon_id = coupon.coupon_id
group by coupon_history.coupon_id
您可以检查每一行的“状态”,以了解它是否超过了 max_used。只是一种不同的方法。
我在这里得到了一个解决方案,但我希望有更多关于其他查询的建议,因为我没有测试效率和有效性。
这是:
SELECT * FROM coupon WHERE coupon_id = 'MY_COUPON_ID' AND
(SELECT COUNT(*) FROM coupon_history) < max_used
select coupon.* from coupon
join
(
select coupon_id, count(*) Count_Coupons_History
from coupon_history
group by coupon_id
) t on (coupon.coupon_id=t.coupon_id)
and (coupon.max_used<=t.Count_Coupons_History)