背景
我有一个包含客户购买记录的表,该表有一个名为coupon_id的列,如果客户在购买期间没有使用优惠券,则此列为null,如果客户使用优惠券id,则为空。该表可以包含单个客户的多个购买,客户可能在一次购买中使用优惠券,而不是在另一次购买期间使用优惠券。
+-------+-------------+-----------+-------------+
| ID | customer_id | coupon_id | other_data |
+-------+-------------+-----------+-------------+
| 0 | 1 | 32 | ... |
| 1 | 1 | null | ... |
| 2 | 1 | null | ... |
| 3 | 1 | null | ... |
| 4 | 2 | null | ... |
| 5 | 3 | 11 | ... |
| 6 | 4 | null | ... |
| 7 | 4 | null | ... |
+-------+-------------+-----------+-------------+
问题
我想得到customer_id的所有客户谁从来没有作出购买使用优惠券。我正在使用的当前查询仍然是返回使用优惠券购买的客户。
SELECT customer_id from checkouts c
WHERE code_id IS NULL
GROUP BY customer_id
ORDER BY customer_id asc
问题
如何为从未使用优惠券购买过的顾客选择独特的身份证列表?
发布于 2013-11-08 02:42:58
使用WHERE NOT EXISTS
和子查询。类似于:
SELECT DISTINCT
customer_id
FROM checkouts c
WHERE NOT EXISTS (
SELECT *
FROM checkouts
WHERE
checkouts.customer_id = c.customer_id
AND coupon_id IS NOT NULL
) cc;
不完全确定这是否是正确的MySQL语法,但这是它的要点。
https://stackoverflow.com/questions/19850633
复制相似问题