1

嗨,我有一个优惠券系统,它使用一个表(称为“优惠券”)来存储有关可以生成的每种可用优惠券的信息,并使用另一个表(生成的优惠券)来存储有关生成的每个优惠券的信息。我很难比较每个表中的信息。

架构:

table: coupons
+----+------+--------------------+---------------+
|  id| owner|     expiration_date| limit_per_user|
|  15|    34| 2011-09-18 00:00:00|              2|
+----+------+--------------------+---------------+

table: generatedcoupons
+----+----------+------+--------------------+------+--------+
|  id| coupon_id| owner|                date|  used| user_id|
|   1|        15|    34| 2011-09-17 00:00:00| false|     233|
+----+----------+------+--------------------+------+--------+

我正在尝试运行查询以从用户的角度显示优惠券(即所有查询都将具有where user_id='$userid'。我不知道如何显示未满足 limit_per_user 的所有优惠券......这就是我的有这行不通:

select * 
from coupons 
where owner=34 
and (count(SELECT * from generatedcoupons where user_id=233 and coupon_id=coupons.id)<limit_per_user)
4

2 回答 2

1

对于 MySQL,join 通常比子查询更快、更可靠,但会让你想得更难一些。这种情况下,需要根据join的行数进行限制,需要进行后分组计算;幸运的是,这正是该HAVING子句的用途:

select coupons.*
from coupons
left join generatedcoupons on user_id = 233 and coupon_id = coupons.id
where coupons.owner = 34
group by coupons.id
having count(generatedcoupons.id) < limit_per_user
于 2011-09-21T20:25:47.780 回答
1
select * 
from coupons as c left join
generatedcoupons as g on g.user_id = 233 and g.coupon_id = c.id
where c.owner=34
group by c.id
having count(g.id) < c.limit_per_user
于 2011-09-21T20:28:42.637 回答