search
HomeDatabaseMysql TutorialWhat are mysql's join query and multiple query methods?

    Comparison between join query and multiple queries

    Which is more efficient, MySQL multi-table related query or multiple single-table query?

    When the amount of data is not large enough, there is no problem in using join, but it is usually done on the service layer.

    First: Stand-alone database computing resources are very expensive, and the database requires Service writing and reading both require CPU consumption. In order to increase the throughput of the database, and the business does not care about the delay gap of hundreds of microseconds to milliseconds, the business will put more calculations into the service layer. After all, Computing resources are easy to expand horizontally, but databases are difficult. Therefore, most businesses will put pure computing operations on the service layer, and use the database as a KV system with transaction capabilities. This is a business-focused, light-weighted system. DB architecture ideas

    Second: Many complex businesses may not use only one database due to historical development reasons. Generally, a layer of middleware will be added to multiple databases. Multiple databases There is no way to join between them. Naturally, the business will abstract a service layer to reduce the coupling to the database.

    Third: For some large companies, due to the large scale of data, they have to divide the database into separate databases and tables. For the application of separate databases and tables, the use of join is also subject to many restrictions, unless the business can be well based on The sharding key makes it clear that the two tables to be joined are in the same physical database. Middleware generally does not support cross-database joins well.

    To give a very common business example, in a sub-database and sub-table, two tables need to be updated synchronously. The two tables are located in different physical libraries. In order to ensure data consistency, one way is to use Distributed transaction middleware puts two update operations into one transaction, but such operations generally require a global lock, which is very slow in performance. However, some businesses can tolerate short-term data inconsistencies. How to do this? Let them be updated separately, but there will be a problem of data writing failure, then start a scheduled task, scan the A table for failed rows, and then see if the B table is also written successfully, and then pair the two associations. Record correction cannot be achieved using join at this time. The data can only be pulled to the service layer and merged by the application itself. . .

    In fact, reconstructing the query by decomposing the associated query has the following advantages:

    Make the cache more efficient.

    Many applications can easily cache the result objects corresponding to single-table queries. In addition, for MySQL's query cache, if a table in the association changes, the query cache cannot be used. After splitting, if a table rarely changes, queries based on the table can be repeated. Use query cache results.

    After breaking down the query, executing a single query can reduce lock contention.

    Making associations at the application layer makes it easier to split the database and achieve high performance and scalability.

    The efficiency of the query itself may also be improved

    Queries that can reduce redundant records.

    Furthermore, this is equivalent to implementing a hash association in the application instead of using MySQL's nested ring association. In some scenarios, hash association is much more efficient.

    Execution order of query statements join, on, where

    Execution order of MySQL

    1. Complete execution order of typical SELECT statements

    1) from sub Sentences assemble data from different data sources;

    2) Use on to filter data for join connections

    3) The where clause filters record rows based on specified conditions;

    4) The group by clause divides the data into multiple groups;

    5) cube, rollup

    6) Use aggregate functions for calculation;

    7) Use The having clause filters grouping;

    8) Calculate all expressions;

    9) Calculate select fields;

    10) Use distinct to deduplicate data

    11) Use order by to sort the result set.

    12) Select TOPN data

    2. from

    If the association is from tableA, tableB, these two tables will first be organized for Cartesian product, and then Perform the following operations such as where and group by.

    3. on

    If you use left join, inner join or outer full join, use on to filter conditions and then join.

    Look at the following 2 sql and results. The difference between the two lies in the position after the on and where statements. First use on for conditional filtering, then perform join operation, and then apply where conditional filtering.

    Use join to connect first, and then use on to filter, which will form a Cartesian product. There is no difference between such a left join and a direct join. So you must first filter on conditions and then join.

    If a JOIN operation is performed after WHERE and above ON, the results of the following two SQL queries should be the same. It can be seen that where is filtering for the set after join.

    To summarize: First perform on condition filtering, then join, and finally perform where filtering

    SELECT DISTINCT a.domain , b.domain
    FROM mal_nxdomains_raw a
    LEFT JOIN mal_nxdomains_detail b ON a.domain = b.domain AND b.date = ‘20160403'
    WHERE a.date = ‘20160403'

    What are mysqls join query and multiple query methods?

    SELECT DISTINCT a.domain , b.domain
    FROM mal_nxdomains_raw a
    LEFT JOIN mal_nxdomains_detail b ON a.domain = b.domain #and b.date = ‘20160403'
    WHERE a.date = ‘20160403'
    AND b.date = ‘20160403'

    What are mysqls join query and multiple query methods?

    四、on 条件与where 条件

    1、使用位置

    • on 条件位置在join后面

    • where 条件在join 与on完成的后面

    2、使用对象

    • on 的使用对象是被关联表

    • where的使用对象可以是主表,也可以是关联表

    3、选择与使用

    主表条件筛选:只能在where后面使用。

    被关联表,如果是想缩小join范围,可以放置到on后面。如果是关联后再查询,可以放置到where 后面。

    如果left join 中,where条件有对被关联表的 关联字段的 非空查询,与使用inner join的效果后,在进行where 筛选的效果是一样的。不能起到left join的作用。

    五、join 流程

    在表A和表B的联接中,从A表中选出一条记录,并将其传递到B表进行扫描和匹配。所以A的行数决定查询次数,B表的行数决定扫描范围。需要运行100次从A表中取出一条数据,然后进行200次比对,将结果存储到B表中。

    相对来说从A表取数据消耗的资源比较多。所以尽量tableA选择比较小的表。同时缩小B表的查询范围。

    但是实际应用中,因为二者返回的数据结果不同,使用的索引也不同,导致条件放置在on 和 where 效率是不一定谁更好。要根据需求来确定。

    The above is the detailed content of What are mysql's join query and multiple query methods?. 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
    Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

    ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

    MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

    MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

    MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

    MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

    MySQL's Purpose: Storing and Managing Data EffectivelyMySQL's Purpose: Storing and Managing Data EffectivelyApr 16, 2025 am 12:16 AM

    MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

    SQL and MySQL: Understanding the RelationshipSQL and MySQL: Understanding the RelationshipApr 16, 2025 am 12:14 AM

    The relationship between SQL and MySQL is the relationship between standard languages ​​and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

    Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

    InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

    What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

    Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

    What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

    Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

    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

    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)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor