Union query: Multiple queries (multiple SELECT statements), stitching on records (fields do not increase)
basic Syntax: Multiple SELECT statement composition: The number of fields that each SELECT statement obtains must be strictly consistent (but field type Independent)
Grammar
Select Statement 1Union [Union option]select Statement 2
Union option: As with the Select option, there are two
All: Keep all (regardless of duplicates)
DISTINCT: deduplication (entire repetition): default
For example
--Table A SELECT * from Prospect;+---------+-------+------------------------+|FName|LName|Addr|+---------+-------+------------------------+|Peter|Jones| 482Rush St., Apt.402 ||Bernice|Smith| 916Maple Dr.|+---------+-------+------------------------+--Table Two SELECT * fromcustomer;+-----------+------------+---------------------+|Last_Name|First_Name|Address|+-----------+------------+---------------------+|Peterson|Grace| 16055Seminole Ave.||Smith|Bernice| 916Maple Dr.||Brown|Walter| 86021st St.|+-----------+------------+---------------------+--Table III SELECT * fromVendor;+-------------------+---------------------+|Company|Street|+-------------------+---------------------+|Reddyparts, Inc.| -Industrial Blvd.||Parts- to-Go, Ltd.|213B Commerce Park.|+-------------------+---------------------+--If all three tables have different column names, the Query methodSELECTfname, lname, addr fromProspectUNIONSELECTFirst_Name, last_name, address fromCustomerUNIONSELECTCompany"', street fromVendor;+-------------------+----------+------------------------+|FName|LName|Addr|+-------------------+----------+------------------------+|Peter|Jones| 482Rush St., Apt.402 ||Bernice|Smith| 916Maple Dr.||Grace|Peterson| 16055Seminole Ave.||Walter|Brown| 86021st St.||Reddyparts, Inc.| | -Industrial Blvd.||Parts- to-Go, Ltd.| |213B Commerce Park.|+-------------------+----------+------------------------+--If you want to select all records, including duplicates, please click the First union keyword SELECTfname, lname, addr fromProspect - UNION All - SELECTFirst_Name, last_name, address fromCustomer - UNION - SELECTCompany"', street fromVendor;
The meaning of a federated query:
1. Query the same table, but the requirements are different: such as inquiring students information, boys height ascending, girls height descending.
2. Multi-table query: The structure of multiple tables is exactly the same, and the stored data (structure) is the same.
Order by uses
In a federated query: the order by cannot be used directly, the query statement needs to use parentheses;
Also, order by takes effect: must be paired with Limit:limit to use the specified maximum number
.
-- the men are ordered by grade, and the women are sorted by flashbacks . (Select*fromwhere gender=orderby99999 )Union(Select*fromwhere gender = Order by 99999)
MySQL Federated Query