search
HomeDatabaseSQLSQL 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!

SQL introductory learning: A brief analysis of the usage of the UNION keyword

#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

SQL introductory learning: A brief analysis of the usage of the UNION keyword

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.

SQL introductory learning: A brief analysis of the usage of the UNION keyword

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`

SQL introductory learning: A brief analysis of the usage of the UNION keyword

##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`

SQL introductory learning: A brief analysis of the usage of the UNION keyword

Data type

As seen above, the number of columns for multiple queries must be The same, then if the number of columns queried is the same but the data type of the query field is different, can it be processed normally? Next, replace pass_word in the s_user query with create_time to query. You can see it after querying. In SQL queries, the data type of the column is irrelevant. Of course, in actual business, they will not be set to different types.

SELECT userid,name,create_time  FROM `s_user` UNION SELECT pass_word,name,userid FROM `s_user_1`

SQL introductory learning: A brief analysis of the usage of the UNION keyword

Column order

 When using the UNION keyword to query, is it related to the order of the columns? As seen above, it may be related to the order of the columns. , it may be irrelevant, so let’s do a test. You can see that the execution results have nothing to do with the order of the columns. In actual business, multiple queries are merged, so the order of columns we define in the project needs to be consistent.

SELECT create_time,userid,name  FROM `s_user` UNION SELECT pass_word,name,userid FROM `s_user_1`

SQL introductory learning: A brief analysis of the usage of the UNION keyword

The difference between UNION and UNION ALL

In order to test the difference between UNION and UNION ALL, you need to add [Xiaobai] to the data table s_user_1, and compare it with the table s_user [Xiaobai] are both stored in the database, what are the different results between the two?

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');

SQL introductory learning: A brief analysis of the usage of the UNION keyword

Execute first:

SELECT user_name,name,pass_word,salt
FROM `s_user` UNION SELECT user_name,name,pass_word,salt FROM `s_user_1`

Execution result:

SQL introductory learning: A brief analysis of the usage of the UNION keyword##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:

SQL introductory learning: A brief analysis of the usage of the UNION keyword 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 tutorial

The 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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
SQL: A Beginner-Friendly Approach to Data Management?SQL: A Beginner-Friendly Approach to Data Management?Apr 19, 2025 am 12:12 AM

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.

SQL in Action: Real-World Examples and Use CasesSQL in Action: Real-World Examples and Use CasesApr 18, 2025 am 12:13 AM

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 and MySQL: Understanding the Core DifferencesSQL and MySQL: Understanding the Core DifferencesApr 17, 2025 am 12:03 AM

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.

SQL: The Learning Curve for BeginnersSQL: The Learning Curve for BeginnersApr 16, 2025 am 12:11 AM

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: The Commands, MySQL: The EngineSQL: The Commands, MySQL: The EngineApr 15, 2025 am 12:04 AM

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.

SQL for Data Analysis: Advanced Techniques for Business IntelligenceSQL for Data Analysis: Advanced Techniques for Business IntelligenceApr 14, 2025 am 12:02 AM

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: A Specific Implementation of SQLMySQL: A Specific Implementation of SQLApr 13, 2025 am 12:02 AM

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.

SQL: Making Data Management Accessible to AllSQL: Making Data Management Accessible to AllApr 12, 2025 am 12:14 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

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

SublimeText3 Mac version

God-level code editing software (SublimeText3)