mysql数据合并关键词union的使用

100人浏览   2024-08-13 12:32:09


一、合并查询union

普通查询我们使用语法结构select字段from表--→返回一个查询结果。第一次使用select得到查询结果1。第二次使用select得到查询结果2。将几次的查询结果合并到总的一个结果中。此时,我们需要使用union关键词。

使用union合并查询的两种方式。第一种:union将查询结果中相同的结果进行合并。第二种:union all不合并相同的结果。

二、合并查询union语法结构与注意事项

(一)语法结构:Select字段from表Union/union all Select字段from表...继续写所有的查询

(二)注意点:这些类似的查询语句,字段的列要相同、列的顺序要相同,值的类型要相似。

(三)案例分享

案例1:将user表和news表的id字段数据进行union all合并

语句:select id from news union all select id fromuser;

案例2:查询user表中nickname等于四川大叔和四川二流子的数据记录。

方法一:select * from user where nickname=’四川大叔’union all select * from user where nickname=’四川二流子’;

方法二:select * from user where nickname in(’四川大叔’,’四川二流子’);

案例3:查询user表Nickname字段中“四川”和“四川大叔”的数据。相同值合并显示一个。

语句:select nickname from user where nickname=’四川’ union select nickname from user where nickname=’四川大叔’

注意:使用union合并查询数据结果,有点类似distinct关键词去重。


相关推荐