首页 > 关于Mysql判断是否存在满足某一条件的记录

关于Mysql判断是否存在满足某一条件的记录

需求

查询哪些用户存在有效的优惠券 即仍未使用且未过期

假如是查询一个用户的话
SQL

select 1 from user_coupon where status = '未使用' and current_date<=ovre_date and user_id = 'XXX' limit 1;

只要有任一行记录满足条件的话即返回1, 表示存在可用的优惠券,无需查询出该用户所有的有效优惠券记录

如果用java表述的话 相当于

for(UserCoupon e : list){
    if(e.status == 未使用 && currentDate <= e.overDate){
        return true;
    }
}

但假如查询条件是一个用户ID列表呢? 这时好像只能用distinctgroup by了,必须要先查询出所有记录了, 没办法做到limit 1

select distinct user_id from user_coupon where ... and user_id in (XXX,XXX,XXX);

selec user_id from user_coupon where ... and user_id in (XXX,XXX,XXX) group by user_id; 

查询条件为列表的情况下 有没办法指定只要有一条记录满足条件即返回 无需查询所有 这样的话 也省了用distinctgroup by


没太看懂问题。如果查询条件是列表的话,你希望返回结果是所有至少有一张优惠券的用户吗?如果是的话,这样写:
select user_id, count(1) as c from user_coupon where ... group by user_id having c > 0 order by null
如果百万级以下的表,速度应该可以接受,但表比较大的情况下可能有性能问题,建议用explain分析一下。

【热门文章】
【热门文章】