檸檬工會
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.pswp.cn/news/389926.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/389926.shtml 英文地址,請注明出處:http://en.pswp.cn/news/389926.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!