MYSQL select unique id's where column value is not null 在一个或多个记录中

标签 mysql sql

背景

我有一个包含客户购买记录的表,该表有一个名为 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/

相关文章:

jquery - jeditable vs editable in datatable - 有什么区别

mysql - 是否可以使用 sequelize 来订购中间关系表?

php - 如何在不依赖 PHP 循环的情况下执行此查询?

mysql - 在输入框中输入错误拼写时返回错误消息

mysql - 为什么 "t1 inner join t2"和 "t1 inner join t3"快,但 "t1 inner join t2 inner join t3"慢 265 倍?

sql - 在 BigQuery 中从数组中减去项目

SQL Server : Select Where String Doesn't Contain Certain Value

mysql - 无法启动 mysqld

sql - 在 SQL 查询 where 子句中使用多个值

mysql - 如何在 MySql 的 limit 子句中使用乘法