user1表spa
user_skill表3d
關聯方式1code
#獲取同時擁有「變化」和「唸經」技能的用戶
select a.user_name, b.skill, c.skill from user1 a join user_skills b on a.id = b.user_id and b.skill = "唸經" join user_skills c on c.user_id = b.user_id and c.skill = "變化" where b.skill_level>0 and c.skill_level>0
執行結果blog
關聯方式2產品
#獲取同時擁有4項技能的用戶,若是沒有顯示null,過濾少於2項技能的用戶
select a.user_name, b.skill, c.skill, d.skill, e.skill from user1 a left join user_skills b on a.id = b.user_id and b.skill = "唸經" and b.skill_level>0 left join user_skills c on a.id = c.user_id and c.skill = "變化" and c.skill_level>0 left join user_skills d on a.id = d.user_id and d.skill = "騰雲" and d.skill_level>0 left join user_skills e on a.id = e.user_id and e.skill = "浮水" and e.skill_level>0 where (case when b.skill is not null then 1 else 0 end) +(case when c.skill is not null then 1 else 0 end) +(case when d.skill is not null then 1 else 0 end) +(case when e.skill is not null then 1 else 0 end) >= 2
執行結果class
group by方式select
#查詢出至少大於等於兩項技能的用戶
select a.id, a.user_name from user1 a join user_skills b on a.id = b.user_id where b.skill in ("唸經","變化","騰雲","浮水") and b.skill_level>0 group by a.user_name having count(*) >= 2
執行結果方法
user1表im
user_kills查詢
join方法
select a.user_name, b.timestr, b.kills from user1 a join user_kills b on a.id = b.user_id join (select user_id,max(kills) as cnt from user_kills group by user_id) c on b.user_id = c.user_id and b.kills = c.cnt
where子句方法
select a.user_name, b.timestr, b.kills from user1 a join user_kills b on a.id = b.user_id where (b.user_id,b.kills) in (select user_id,max(kills) as cnt from user_kills group by user_id);
執行結果
kills殺怪個數
where型的子查詢就是把內層查詢的結果看成外層查詢的條件
lc_user表
3.1 查詢每類理財產品理財金額最高的兩個客戶
SELECT * FROM lc_user as a WHERE 2>(SELECT count(*) FROM lc_user WHERE LoanType = a.LoanType and Amount > a.Amount) order BY a.LoanType, a.Amount DESC
上面的語句至關於依次執行了一遍下面的SQL
#第一次比較A001 SELECT count(*) FROM lc_user a where LoanType = "A001" and Amount > 100 # 2>2 SELECT count(*) FROM lc_user a where LoanType = "A001" and Amount > 1000 # 2>1 SELECT count(*) FROM lc_user a where LoanType = "A001" and Amount > 5000 # 2>0 #第二次比較A002 SELECT count(*) FROM lc_user a where LoanType = "A002" and Amount > 100 # 2>2 SELECT count(*) FROM lc_user a where LoanType = "A002" and Amount > 500 # 2>1 SELECT count(*) FROM lc_user a where LoanType = "A002" and Amount > 1000 # 2>0 #第三次比較A003 SELECT count(*) FROM lc_user a where a.LoanType = "A003" and a.Amount > 2000 # 2>0
執行結果