2 Star 0 Fork 0

wscaco3 / mysql_tech

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
zi_pi_pei.md 1.03 KB
一键复制 编辑 原始数据 按行查看 历史
wscaco3 提交于 2015-11-19 14:07 . Update zi_pi_pei.md

子查询匹配两个值

定义

当一个查询是另一个查询的条件时,称之为子查询。

常见的使用场景

  1. 使用子查询可以避免由于子查询中的数据产生的重复

     select user_name from user1 where id in (select user_id from user_kills);
     select distinct user_name from user1 a join user_kills b on a.id = b.user_id;
  2. 使用子查询更符合语意,更好理解

查询出每一个取经人打怪最多的日期,并列出取经人的姓名,打怪最多的日期和打怪数量

select a.user_name,b.killday,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;

mysql中独有的多例过滤方式

select a.user_name,b.killday,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) from user_kills group by user_id);
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wscaco3/mysql_tech.git
git@gitee.com:wscaco3/mysql_tech.git
wscaco3
mysql_tech
mysql_tech
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891