美文网首页
mysql进阶操作join篇(三)

mysql进阶操作join篇(三)

作者: 堂哥000 | 来源:发表于2021-12-20 11:10 被阅读0次
本文主要介绍mysql中常用join和in,exists 的转化

mysql 版本:\color{red}{mysql Ver 8.0.27 for Win64 on x86_64 (MySQL Community Server - GPL)}
\color{red}{注意: 使用5.7 以下版本建表是不支持两个时间戳字段的}

  • 建表

-- 建表
CREATE TABLE `product_name_copy` (
  `id` bigint NOT NULL DEFAULT '0',
  `name` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '产品名',
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

\color{red}{使用单列的文件在navicat里可视化录入数据}

  • left join

-- 查询A表有而B表没有的数据
select * from demo.product_name_copy a left join demo.product_name b on a.name = b.name  where b.name is null ;
select * from demo.product_name_copy a left outer join demo.product_name b on a.name = b.name  where b.name is null ;
select * from demo.product_name_copy  a  where a.name not  in (select name from demo.product_name) ;
select * from demo.product_name_copy  a  where not EXISTS(select name from demo.product_name b where a.name = b.name) ;
  • right join

-- 查询A表没有而B表有的数据
select * from demo.product_name a right join demo.product_name_copy b on a.name = b.name  where a.name is null ;
  • inner join

-- 查询A和B表同时存在的数据
select * from demo.product_name_copy a  join demo.product_name b on a.name = b.name ;
select * from demo.product_name_copy a inner join demo.product_name b on a.name = b.name ;
select * from demo.product_name_copy  a  where a.name  in (select name from demo.product_name) ;
select * from demo.product_name_copy  a  where exists(select * from demo.product_name b where a.name = b.name )  ;
  • full join (\color{red}{mysql本身不存在full join})

-- mysql 不存在full join 
-- full join  
-- full join 原始写法1 , 1=1 写法慎用,会出现笛卡尔积,内存爆炸
select * fr om demo.product_name_copy a  FULL JOIN   demo.product_name b on 1=1; -- 写法不存在
-- full join  替代方案1
select * from demo.product_name_copy a left join demo.product_name b on  1=1
union 
select * from demo.product_name_copy a right join demo.product_name b on 1=1
;
-- full join原始写法2
select * from demo.product_name_copy a  FULL JOIN   demo.product_name b on a.name=b.name; -- 写法不存在
-- full join替代方案2
select * from demo.product_name_copy a left join demo.product_name b on  a.name=b.name
union 
select * from demo.product_name_copy a right join demo.product_name b on a.name=b.name;

相关文章

网友评论

      本文标题:mysql进阶操作join篇(三)

      本文链接:https://www.haomeiwen.com/subject/ziaafrtx.html