3

我的数据库中有这些结构:

Table coupon
coupon_id , code, max_used

Table coupon_history
coupon_history_id, coupon_id, used_date

我可以在“coupon.max_used”不超过“coupon_history”的总历史的情况下获取优惠券数据吗?我被困在这里。我需要一个优惠券代码。请帮我。

4

4 回答 4

2

尝试使用JOININ像这样:

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;

看看这个 SQLFiddle 演示


编辑:关于你的第二个要求

试试这个查询:

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;

看到这个 SQLFiddle

于 2013-07-05T08:19:02.907 回答
1

你可以试试下面:

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。只是一种不同的方法。

SQL小提琴:http ://www.sqlfiddle.com/#!2/a5d0d/25

于 2013-07-05T08:02:48.403 回答
0

我在这里得到了一个解决方案,但我希望有更多关于其他查询的建议,因为我没有测试效率和有效性。

这是:

SELECT * FROM coupon WHERE coupon_id = 'MY_COUPON_ID' AND 
      (SELECT COUNT(*) FROM coupon_history) < max_used
于 2013-07-05T08:14:12.147 回答
0
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)
于 2013-07-05T08:15:31.397 回答