SQL introductory learning: A brief analysis of the usage of the UNION keyword
During our development process, we often use multiple query results to be displayed directly. So how should we query? This article is about learning SQL. Let’s take a look at the UNION keyword in SQL and how to use it. I hope it will be helpful to everyone!
#The UNION keyword in SQL will display the results of multiple query conditions.
UNION
The Chinese meaning of UNION is union, that is, merging the results of two or more SELECT statements. The usage tips are as follows:
- Each SELECT statement inside a UNION must have the same number of columns.
- Columns must have similar data types.
- The order of the columns in each SELECT statement must be the same.
The same number of columns
As shown below, use the data introduced in the previous chapter as demonstration data
Create tables respectively s_user
and table s_user_1
CREATE TABLE `s_user` ( `userid` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `pass_word` varchar(255) DEFAULT NULL, `salt` varchar(255) DEFAULT NULL, `state` varchar(255) DEFAULT NULL, `create_time` datetime DEFAULT NULL, PRIMARY KEY (`userid`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
The test data is as follows:
INSERT INTO `test`.`s_user`(`userid`, `user_name`, `name`, `pass_word`, `salt`, `state`, `create_time`) VALUES (1, '小米', '小米', '123123', '123', '1', '2022-02-10 19:48:43'); INSERT INTO `test`.`s_user`(`userid`, `user_name`, `name`, `pass_word`, `salt`, `state`, `create_time`) VALUES (2, '小白', '小白', '123123', '123', '1', '2022-02-10 19:48:43'); INSERT INTO `test`.`s_user_1`(`userid`, `user_name`, `name`, `pass_word`, `salt`, `state`, `create_time`) VALUES (1, '小红', '小红', '123123', '123', '1', '2022-02-10 19:48:43'); INSERT INTO `test`.`s_user_1`(`userid`, `user_name`, `name`, `pass_word`, `salt`, `state`, `create_time`) VALUES (2, '小黄', '小黄', '123123', '123', '1', '2022-02-10 19:48:43');
Each SELECT statement inside UNION must have the same number of columns: query first SQL
SELECT * FROM `s_user` UNION SELECT * FROM `s_user_1`
with the same columns queries all columns. You can see that the execution results are as follows.
If the first query is for all columns and the second query is for three fields, what is the query result? Now execute the following SQL:
Error usage
SELECT * FROM `s_user` UNION SELECT userid,name,pass_word FROM `s_user_1`
##Error message: The SELECT statement used to query a different number of columns
Correct usage
SELECT userid,name,pass_word FROM `s_user` UNION SELECT userid,name,pass_word FROM `s_user_1`
SELECT userid,name,create_time FROM `s_user` UNION SELECT pass_word,name,userid FROM `s_user_1`
SELECT create_time,userid,name FROM `s_user` UNION SELECT pass_word,name,userid FROM `s_user_1`
INSERT INTO `test`.`s_user_1`(`userid`, `user_name`, `name`, `pass_word`, `salt`, `state`, `create_time`) VALUES (3, '小白', '小白', '123123', '123', '1', '2022-02-10 19:48:43');
SELECT user_name,name,pass_word,salt FROM `s_user` UNION SELECT user_name,name,pass_word,salt FROM `s_user_1`Execution result:
##Execute again
SELECT user_name,name,pass_word,salt FROM `s_user` UNION ALL SELECT user_name,name,pass_word,salt FROM `s_user_1`
Execution results:
You can see that UNION association removes duplicate items, while UNION ALL queries all values without removing duplicate data.
Conclusion
Okay, the above is the usage of the UNION keyword in SQL. Thank you for reading. I hope you like it. If it is helpful to you, please like and collect it. If there are any deficiencies, please comment and correct them. See you next time.
Recommended learning:
mysql video tutorialThe above is the detailed content of SQL introductory learning: A brief analysis of the usage of the UNION keyword. For more information, please follow other related articles on the PHP Chinese website!

SQL is suitable for beginners because it is simple in syntax, powerful in function, and widely used in database systems. 1.SQL is used to manage relational databases and organize data through tables. 2. Basic operations include creating, inserting, querying, updating and deleting data. 3. Advanced usage such as JOIN, subquery and window functions enhance data analysis capabilities. 4. Common errors include syntax, logic and performance issues, which can be solved through inspection and optimization. 5. Performance optimization suggestions include using indexes, avoiding SELECT*, using EXPLAIN to analyze queries, normalizing databases, and improving code readability.

In practical applications, SQL is mainly used for data query and analysis, data integration and reporting, data cleaning and preprocessing, advanced usage and optimization, as well as handling complex queries and avoiding common errors. 1) Data query and analysis can be used to find the most sales product; 2) Data integration and reporting generate customer purchase reports through JOIN operations; 3) Data cleaning and preprocessing can delete abnormal age records; 4) Advanced usage and optimization include using window functions and creating indexes; 5) CTE and JOIN can be used to handle complex queries to avoid common errors such as SQL injection.

SQL is a standard language for managing relational databases, while MySQL is a specific database management system. SQL provides a unified syntax and is suitable for a variety of databases; MySQL is lightweight and open source, with stable performance but has bottlenecks in big data processing.

The SQL learning curve is steep, but it can be mastered through practice and understanding the core concepts. 1. Basic operations include SELECT, INSERT, UPDATE, DELETE. 2. Query execution is divided into three steps: analysis, optimization and execution. 3. Basic usage is such as querying employee information, and advanced usage is such as using JOIN connection table. 4. Common errors include not using alias and SQL injection, and parameterized query is required to prevent it. 5. Performance optimization is achieved by selecting necessary columns and maintaining code readability.

SQL commands are divided into five categories in MySQL: DQL, DDL, DML, DCL and TCL, and are used to define, operate and control database data. MySQL processes SQL commands through lexical analysis, syntax analysis, optimization and execution, and uses index and query optimizers to improve performance. Examples of usage include SELECT for data queries and JOIN for multi-table operations. Common errors include syntax, logic, and performance issues, and optimization strategies include using indexes, optimizing queries, and choosing the right storage engine.

Advanced query skills in SQL include subqueries, window functions, CTEs and complex JOINs, which can handle complex data analysis requirements. 1) Subquery is used to find the employees with the highest salary in each department. 2) Window functions and CTE are used to analyze employee salary growth trends. 3) Performance optimization strategies include index optimization, query rewriting and using partition tables.

MySQL is an open source relational database management system that provides standard SQL functions and extensions. 1) MySQL supports standard SQL operations such as CREATE, INSERT, UPDATE, DELETE, and extends the LIMIT clause. 2) It uses storage engines such as InnoDB and MyISAM, which are suitable for different scenarios. 3) Users can efficiently use MySQL through advanced functions such as creating tables, inserting data, and using stored procedures.

SQLmakesdatamanagementaccessibletoallbyprovidingasimpleyetpowerfultoolsetforqueryingandmanagingdatabases.1)Itworkswithrelationaldatabases,allowinguserstospecifywhattheywanttodowiththedata.2)SQL'sstrengthliesinfiltering,sorting,andjoiningdataacrosstab


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)