背景
我有一个包含客户购买记录的表,该表有一个名为 coupon_id 的列,如果客户在购买过程中没有使用优惠券,则该列为空,如果使用,则包含优惠券 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
问题
如何为从未使用优惠券购买过的客户选择唯一 ID 列表?
最佳答案
使用 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 语法,但这就是它的要点。
关于MYSQL select unique id's where column value is not null 在一个或多个记录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19850633/