2011-09-22 27 views
0

您好我有一个使用一个表(称为“优惠券”)存储每个类型的可用优惠券,人们可以产生的信息的优惠券系统,和另一个表(generatedcoupons)来存储有关每个优惠券的信息。我很难比较每张表中的信息。MySQL的加入问题 - 我是这样做的权利

的模式:

table: coupons 
+----+------+--------------------+---------------+ 
| id| owner|  date_expiration| 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| 
+----+----------+------+--------------------+------+--------+ 

我想选择所有过期的优惠券给定用户。它是否正确?

select * 
from coupons 
join generatedcoupons on user_id = 233 and coupon_id=coupons.id 
where coupons.owner=34 and (curdate()>date(coupons.date_expiration) 

回答

1

您需要加入所有者和优惠券ID。然后把你想要过滤的值放在where子句中。

select * 
from coupons c 
join generatedcoupons g on c.owner=g.owner and g.coupon_id=c.id 
where g.user_id = 233 and c.owner=34 and (curdate()>date(c.expiration_date) 
+0

@'Larry Lustig'我无法回复您的帖子,所以我必须回复我的意见。你是对的语法错误和评论3和4.我纠正了我的查询重写语法错误。关于声明3,有时这是故意做的,以滤除结果。例如,如果优惠券只能由其生成的人使用,但拥有它的人不是其生成者。但是,在这种情况下,我不认为这是事实,我同意你的看法。 –

1

有几件事情:

  1. 你的SQL有一个错误,因为该列的名称是到期日期不date_expiration。

  2. 如果coupon_id 15的所有者总是(定义)所有者34,那么你不应该在generatedcoupons表重复所有者列。这样做是多余的,并可能产生在两个表中,你有没有办法找出正确的数据是什么这样的方式不同意的情况。

  3. 您正确理解查询的JOIN部分和查询的WHERE部分,但是您在JOIN部分而不是WHERE部分中放置了过滤条件(user_id = 123)。

  4. 您标记您的问题嵌套查询,但问题实际上并不涉及任何嵌套查询,而是一个简单的JOIN。