1

こんにちは私は、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 の場合、結合は通常、サブクエリよりも高速で信頼性が高くなりますが、少し難しくなります。この場合、結合された行の数に基づいて制限する必要があります。これには、グループ化後の計算が必要です。幸いなことに、それがまさにこの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 に答える