您的位置:首頁技術文章
文章詳情頁

關于Mysql判斷是否存在滿足某一條件的記錄

瀏覽:84日期:2022-06-21 15:08:29

問題描述

需求

查詢哪些用戶存在有效的優惠券 即仍未使用且未過期

假如是查詢一個用戶的話 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列表呢? 這時好像只能用distinct或group 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;

查詢條件為列表的情況下 有沒辦法指定只要有一條記錄滿足條件即返回 無需查詢所有 這樣的話 也省了用distinct和group by了

問題解答

回答1:

沒太看懂問題。如果查詢條件是列表的話,你希望返回結果是所有至少有一張優惠券的用戶嗎?如果是的話,這樣寫:select user_id, count(1) as c from user_coupon where ... group by user_id having c > 0 order by null如果百萬級以下的表,速度應該可以接受,但表比較大的情況下可能有性能問題,建議用explain分析一下。

相關文章:
国产综合久久一区二区三区