联合查询简单说 就是将两次查询合并在一起

例如 我们这里有一个用户表

MySQL联合查询实现方法详解

我们先编写一段SQL

select name from staff where age > 21;

查询年龄大于21的 输出结果如下

MySQL联合查询实现方法详解

然后我们再写一段sql

select name from staff where status =1;

查询 status 状态字段等于1 的 输出效果如下

MySQL联合查询实现方法详解

然后我们可以二合一一下

select name from staff where age > 21
union all
select name from staff where status =1;

输出结果如下

MySQL联合查询实现方法详解

这是 我们两段sql就二合一了

但我发现 因为张三两个条件都达到了 所以他被查询出了两次

如果想去重 我们只需要将 all去掉

参考代码如下

select name from staff where age > 21
union
select name from staff where status =1;

查询结果如下

MySQL联合查询实现方法详解

这样就完成去重了

但现在 我们上下 字段列表查的都是 name

如果我们将代码改成这样

select * from staff where age > 21
union
select name from staff where status =1;

一个就查name 一个查全部 *

但这样就报错了

MySQL联合查询实现方法详解

我们将两个都改成 *

select * from staff where age > 21
union
select * from staff where status =1;

MySQL联合查询实现方法详解

这样就可以查到了

说明 联合查询 多次查询的字段列表必须是一样的

原文地址:https://blog.csdn.net/weixin_45966674/article/details/127469424

相关文章:

  • 2022-12-23
  • 2021-10-14
  • 2022-12-23
  • 2022-03-13
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
猜你喜欢
  • 2022-12-23
  • 2021-11-06
  • 2022-01-10
  • 2022-01-21
  • 2022-12-23
相关资源
相似解决方案