MySQL获取尚未使用的优惠券
我有3个MySQL表,其中包含关于用户、优惠券信息以及用户是否使用优惠券的信息。类似这样的内容:MySQL获取尚未使用的优惠券,mysql,sql,join,Mysql,Sql,Join,我有3个MySQL表,其中包含关于用户、优惠券信息以及用户是否使用优惠券的信息。类似这样的内容: 用户表 +----------+-------------+ | User_ID | Name | +----------+-------------+ | 1 | Sarah J | | 2 | John Smith | | 3 | Osman Lee | +----------+-------------+ +------
用户表
+----------+-------------+
| User_ID | Name |
+----------+-------------+
| 1 | Sarah J |
| 2 | John Smith |
| 3 | Osman Lee |
+----------+-------------+
+----------+-------------+
| Coupon_ID| Title |
+----------+-------------+
| 1 | Free Stuff |
| 2 | 50% Off |
| 3 | $5 off $25 |
+----------+-------------+
优惠券表+----------+-------------+
| User_ID | Name |
+----------+-------------+
| 1 | Sarah J |
| 2 | John Smith |
| 3 | Osman Lee |
+----------+-------------+
+----------+-------------+
| Coupon_ID| Title |
+----------+-------------+
| 1 | Free Stuff |
| 2 | 50% Off |
| 3 | $5 off $25 |
+----------+-------------+
和兑换表+----------+---------+----------+
| Coupon_ID| User_ID | Redeemed |
+----------+---------+----------+
| 1 | 1 | yes |
| 2 | 2 | yes |
| 1 | 2 | yes |
+----------+---------+----------+
基本上,我希望每个用户都有这样的输出:莎拉J:优惠券2和3
约翰·史密斯:优惠券3
李奥斯曼:优惠券1、2和3
我试着使用连接,但到目前为止运气不好。有什么建议吗?[为莎拉]
SELECT Coupons.coupon_id, Coupons.title
FROM Coupons
LEFT JOIN Redeemed ON Redeemed.coupon_id != Coupons.coupon_id
WHERE Users.user_id = '1'
其思想是生成所有行,然后删除存在的行--
交叉连接
和左连接
:
select u.user_id, c.coupon_id as not_used_coupon_id
from coupons c cross join
users u left join
redeemed r
on r.coupon_id = c.coupon_id an dr.user_id = u.user_id
where r.coupon_id is null;
您可以在用户表中添加
where
子句。我假设优惠券和用户之间的所有关系都在兑换表中。
如果是这种情况,则可以简单地使用内部联接
,如下所示:
SELECT Coupons.coupon_id, Coupons.title
FROM Redeemed r
INNER JOIN Users u ON
u.User_ID = r.User_ID
INNER JOIN Coupons c ON
c.Coupon_ID = r.Coupon_ID
where r.Redeemed = 'No'
我假设,对于未赎回的优惠券,赎回的价值可能为“否”
我希望这有助于