SQL开发技巧
1. 同一属性的多值过滤
user1表
user_skill表
关联方式1
#获取同时拥有“变化”和“念经”技能的用户
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
执行结果
关联方式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
执行结果
group by方式
#查询出至少大于等于两项技能的用户
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
执行结果
2. 如何在子查询中匹配两个值
user1表
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杀怪个数
3.where语句中的子查询
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
执行结果