Home Database Mysql Tutorial What to use instead of in in mysql

What to use instead of in in mysql

Oct 05, 2020 am 10:04 AM
mysql

In Mysql, exists is used instead of in; exists uses loop to query the external table one by one. Each query will check the conditional statement of exists. When the conditional statement in exists can return the record row, the condition is true and the current state is returned. loop to this record.

What to use instead of in in mysql

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

exists uses loop to query the external table one by one. Each query will check the conditional statement of exists. When the conditional statement in exists can return the record row (no matter how many record rows there are, as long as it can be returned), the condition will be If true, the record in the current loop is returned. Otherwise, if the conditional statement in exists cannot return the record row, the record in the current loop is discarded. The condition of exists is like a bool condition. When the result set can be returned, is true, if the result set cannot be returned, it is false

As follows:

select * from user where exists (select 1);
Copy after login

The records of the user table are taken out one by one. Since select 1 in the sub-condition can always return record rows, then the user table All records will be added to the result set, so it is the same as select * from user;

And as follows

select * from user where exists (select * from user where userId = 0);
Copy after login

You can know that when looping the user table, check the conditional statement (select * from user where userId = 0), since userId is never 0, the conditional statement will always return the empty set, and the condition will always be false, then all records in the user table will be discarded

not exists is the opposite of exists, and also That is, when the exists condition returns a result set, the looped records will be discarded, otherwise the looped records will be added to the result set

In general, if table A has n records, then the exists query is Take out these n records one by one, and then judge the exists condition n times

in query is equivalent to the superposition of multiple or conditions. This is easier to understand, such as the following query

select * from user where userId in (1, 2, 3);
Copy after login

Equivalent to

select * from user where userId = 1 or userId = 2 or userId = 3;
Copy after login

not in is the opposite of in, as follows

select * from user where userId not in (1, 2, 3);
Copy after login

Equivalent to

select * from user where userId != 1 and userId != 2 and userId != 3;
Copy after login

In general, the in query is to first combine the subquery conditions All the records of are found. Assume that the result set is B, with a total of m records. Then the result set of the subquery condition is decomposed into m, and then m queries are performed.

It is worth mentioning that the in query The return result of the sub-condition must have only one field, such as

select * from user where userId in (select id from B);
Copy after login

but not

select * from user where userId in (select id, age from B);
Copy after login

. However, exists does not have this restriction.

Let’s consider the performance of exists and in.

Consider the following SQL statement

1: select * from A where exists (select * from B where B.id = A.id);

2: select * from A where A.id in (select id from B);

Query 1. You can convert the following pseudo code for easy understanding

for ($i = 0; $i < count(A); $i++) {
  $a = get_record(A, $i); #从A表逐条获取记录
  if (B.id = $a[id]) #如果子条件成立
    $result[] = $a;
}
return $result;
Copy after login

This is probably what it means. In fact, you can see that Query 1 is mainly The index of table B is used. How table A has little impact on the efficiency of the query

Assume that all the ids of table B are 1,2,3, query 2 can be converted into

select * from A where A.id = 1 or A.id = 2 or A.id = 3;
Copy after login

This It’s easy to understand. The index of A is mainly used here. How table B has little impact on the query

Let’s look at not exists and not in

1. select * from A where not exists (select * from B where B.id = A.id);

2. select * from A where A.id not in (select id from B);

Looking at query 1, it is still the same as above, using the index of B

And for query 2, it can be converted into the following statement

select * from A where A.id != 1 and A.id != 2 and A.id != 3;
Copy after login

You can know that not in is a Range query, this != range query cannot use any index, which means that each record in table A must be traversed once in table B to check whether the record exists in table B

so not exists is more efficient than not in

The in statement in mysql is a hash connection between the external table and the internal table, while the exists statement is a loop loop on the external table, and the internal table is queried each time the loop loops. Everyone has always believed that exists is more efficient than the in statement. This statement is actually inaccurate. This depends on the environment.

If the two tables queried are of the same size, there is not much difference between using in and exists.

If one of the two tables is smaller and the other is a large table, use exists for the larger subquery table and in for the smaller subquery table:

For example: Table A (small table ), Table B (large table)

1:

select * from A where cc in (select cc from B) is inefficient and uses the index of the cc column on table A;

select * from A where exists(select cc from B where cc=A.cc) is efficient and uses the index of the cc column on table B.

The opposite

2:

select * from B where cc in (select cc from A) is highly efficient and uses the index of the cc column on table B;

select * from B where exists(select cc from A where cc=B.cc) is inefficient and uses the index of the cc column on table A.

not in and not exists If the query statement uses not in, then the entire table will be scanned on both the inner and outer tables without using the index; and the subquery of not extsts can still use the index on the table. So no matter which table is big, using not exists is faster than not in.

The difference between in and =

select name from student where name in ('zhang','wang','li','zhao');

select name from student where name='zhang' or name='li' or name='wang' or name='zhao'

The results are the same.

Recommended tutorial: mysql video tutorial

The above is the detailed content of What to use instead of in in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

How to view mysql How to view mysql Apr 08, 2025 pm 07:21 PM

View the MySQL database with the following command: Connect to the server: mysql -u Username -p Password Run SHOW DATABASES; Command to get all existing databases Select database: USE database name; View table: SHOW TABLES; View table structure: DESCRIBE table name; View data: SELECT * FROM table name;

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

See all articles