2011-09-21 203 views
1

您好我有一个优惠券系统,使用一个表(称为“优惠券”)存储有关每种可用的优惠券,可以生成的信息和另一个表(generatedcoupons)存储有关每个优惠券的信息。我很难比较每张表中的信息。Mysql嵌套查询传递一个值嵌套查询

的模式:

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) 

回答

1

对于MySQL,加入通常比子查询更快,更可靠,但会让你觉得有点困难在这种情况下,您需要根据加入的ro的数量进行限制ws,这需要后分组计算;幸运的是,这恰恰是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
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