关于Mysql判断是否存在满足某一条件的记录
PHP中文网
PHP中文网 2017-04-17 14:49:43
[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

PHP中文网
PHP中文网

认证0级讲师

全部回复(1)
高洛峰

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号