柠檬工会
Hey guys! This week we’ll be going over some ways to work with result sets in MySQL. These result sets are the outputs of your everyday queries, such as:
大家好! 本周,我们将介绍一些在MySQL中处理结果集的方法。 这些结果集是您日常查询的输出,例如:
联盟 (UNION)
One way to combine two result sets is by using the UNION operator. By default, this combines two result sets without duplicating any rows. This works as you would believe it would in set theory. The syntax for this would be:
合并两个结果集的一种方法是使用UNION运算符。 默认情况下,这将合并两个结果集,而不会重复任何行。 正如您所相信的那样,这会起作用。 语法如下:
Where you have your regular SELECT statements, but use UNION to combine each result set. Each UNION can be followed by either DISTINCT or ALL. DISTINCT will combine the sets but keep each unique value only once, while ALL will combine the sets while keeping duplicates. If you don’t specify either, DISTINCT is used, which is pretty intuitive.
在具有常规SELECT语句的位置,但使用UNION合并每个结果集。 每个UNION后面都可以加上DISTINCT或ALL 。 DISTINCT将合并集合,但每个唯一值仅保留一次,而ALL将合并集合,同时保留重复项。 如果您未指定任何一个,则使用DISTINCT ,这非常直观。
Do note that each SELECT statement should have the same number of columns selected and the data types of the columns should be compatible.
请注意,每个SELECT语句应选择相同数量的列,并且列的数据类型应兼容。
Now let’s look at an example using this. Let’s say we have two tables, table1 and table2, as shown below:
现在让我们来看一个使用此示例。 假设我们有两个表,table1和table2,如下所示:
If we were to combine both columns, col1 and col2, from each table, by following the syntax:
如果我们要通过遵循以下语法将每个表中的列col1和col2组合在一起:
Will produce the following:
将产生以下内容:
Also note that the result’s column names will match those of the first SELECT statement. We can also use aliasing to change this by aliasing the column names of the first SELECT statement.
还要注意,结果的列名将与第一个SELECT语句的列名匹配。 我们还可以使用别名来更改别名,方法是对第一个SELECT语句的列名进行别名处理。
You may have noticed that UNION is similar to JOIN. They both merge your data. However, UNION combines sets vertically, while JOIN combines sets horizontally, as illustrated below:
您可能已经注意到UNION与JOIN类似。 他们都合并您的数据。 但是,UNION垂直组合集合,而JOIN水平组合集合,如下所示:
Now we know how to combine different result sets into a single one!
现在我们知道如何将不同的结果集组合为一个!
The following resource is a huge help for anything SQL related!
以下资源对于任何与SQL相关的问题都是巨大的帮助!
翻译自: https://medium.com/@gl7526/the-union-operator-4721f2ca3482
柠檬工会
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/389926.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!