您好我有一个优惠券系统,它使用一个表(称为“优惠券”)来存储关于可以生成的每种类型的可用优惠券的信息,以及另一个表(生成的优惠券)来存储关于生成的每个优惠券的信息。我很难比较每个表格中的信息。
模式:
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)
答案 0 :(得分:1)
对于MySQL,加入通常比子查询更快,更可靠,但会让你觉得有点困难。在这种情况下,您需要根据连接的行数限制,这需要进行后分组计算;幸运的是,这正是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
答案 1 :(得分: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