關(guān)于Mysql判斷是否存在滿足某一條件的記錄
問(wèn)題描述
需求
查詢哪些用戶存在有效的優(yōu)惠券 即仍未使用且未過(guò)期
假如是查詢一個(gè)用戶的話 SQL
select 1 from user_coupon where status = ’未使用’ and current_date<=ovre_date and user_id = ’XXX’ limit 1;
只要有任一行記錄滿足條件的話即返回1, 表示存在可用的優(yōu)惠券,無(wú)需查詢出該用戶所有的有效優(yōu)惠券記錄
如果用java表述的話 相當(dāng)于
for(UserCoupon e : list){ if(e.status == 未使用 && currentDate <= e.overDate){return true; }}
但假如查詢條件是一個(gè)用戶ID列表呢? 這時(shí)好像只能用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;
查詢條件為列表的情況下 有沒辦法指定只要有一條記錄滿足條件即返回 無(wú)需查詢所有 這樣的話 也省了用distinct和group by了
問(wèn)題解答
回答1:沒太看懂問(wèn)題。如果查詢條件是列表的話,你希望返回結(jié)果是所有至少有一張優(yōu)惠券的用戶嗎?如果是的話,這樣寫:select user_id, count(1) as c from user_coupon where ... group by user_id having c > 0 order by null如果百萬(wàn)級(jí)以下的表,速度應(yīng)該可以接受,但表比較大的情況下可能有性能問(wèn)題,建議用explain分析一下。
相關(guān)文章:
1. bootstrp是col-md-12列的,只有col-md-10有內(nèi)容,可以讓沒有內(nèi)容的不占據(jù)位置嗎;2. android - Genymotion 微信閃退 not find plugin.location_google.GoogleProxyUI3. wordpress里,這樣的目錄列表是屬于小工具還是啥?4. python - Fiddler+Android模擬器抓取app,json數(shù)據(jù)被加密了,如何解析?5. python如何設(shè)置一個(gè)隨著系統(tǒng)時(shí)間變化的動(dòng)態(tài)變量?6. 我的怎么不顯示啊,話說(shuō)有沒有QQ群什么的7. mysql federated引擎無(wú)法開啟8. MySQL 使用 group by 之后然后 IFNULL(COUNT(*),0) 為什么還是會(huì)獲得 null9. 常量在外面不加引號(hào)會(huì)報(bào)錯(cuò)。10. sublime text3安裝package control失敗
