从其他表中选择具有条件规则(计数)的数据

时间:2013-07-05 07:49:22

标签: php mysql sql

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

Table coupon
coupon_id , code, max_used

Table coupon_history
coupon_history_id, coupon_id, used_date

我可以获得优惠券数据,其中“coupon.max_used”不超过“coupon_history”的总历史记录吗? 我被困在这里。我需要获得coupon_code。请帮帮我。

4 个答案:

答案 0 :(得分: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;

查看this SQLFiddle demo


修改:关于您的second requirement

尝试此查询:

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;

请参阅this SQLFiddle

答案 1 :(得分: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

答案 2 :(得分:0)

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

这是:

SELECT * FROM coupon WHERE coupon_id = 'MY_COUPON_ID' AND 
      (SELECT COUNT(*) FROM coupon_history) < max_used

答案 3 :(得分: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)