Common expression optimization methods, apparatus, equipment, storage media, and program products

By recursively traversing the target column expression and aggregate function expression in the database query tree and identifying common expressions, subquery nodes are generated to replace duplicate calculations, thus solving the problem of duplicate calculations in the database and improving query efficiency and resource utilization.

CN123115201APending Publication Date: 2026-11-17CETC JINCANG (BEIJING) TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611257071.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-18
Publication Date
2026-11-17

AI Technical Summary

Technical Problem

In existing technologies, databases fail to effectively identify and extract common expressions in target columns or aggregate functions when processing complex queries, leading to repeated calculations and affecting query response time and resource utilization. This problem is particularly pronounced in scenarios involving multiple table joins or subqueries.

Method used

By receiving the initial query statement and parsing it into a query tree, the target column expression and aggregate function expression are recursively traversed, the reference position of the common expression is identified and recorded, and a subquery node containing the common expression is generated and inserted into the query tree to replace the duplicate calculation part.

Benefits of technology

In scenarios involving multiple nesting and complex calculations, it accurately identifies and processes repetitive expressions, reduces redundant calculation overhead, lowers query optimization complexity, and ensures the semantic correctness of query results.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123115201A_ABST
    Figure CN123115201A_ABST
Patent Text Reader

Abstract

This application provides a common expression optimization method, apparatus, device, storage medium, and program product, relating to the field of database query optimization. Addressing the problems of existing solutions' insufficient identification of repeated sub-expressions in target column expressions and aggregate function expressions, leading to excessive redundant calculations and inadequate optimization rewriting in complex queries, the following solution is proposed: The initial query statement is parsed into a query tree; the expression structure in the target column and aggregate calculations is recursively analyzed; repeatedly occurring common expressions and their reference positions are identified; and sub-query nodes containing common expressions are constructed accordingly, and the query tree is rewritten. This solution improves the ability to identify common items and rewrite queries, reduces redundant evaluations, lowers CPU and memory overhead, and improves the execution efficiency and system throughput of complex queries while ensuring the correctness of query semantics.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of database query optimization, and in particular to a common expression optimization method, apparatus, device, storage medium, and program product. Background Technology

[0002] In Database Management Systems (DBMS), query optimization is a core aspect of improving system performance. When a user submits an SQL query containing complex expressions or aggregate functions, the database kernel needs to parse and optimize the expressions in the query tree to reduce redundant calculations and resource consumption. Because common expressions are not extracted, the database performs repeated calculations during execution, wasting CPU and memory resources and impacting query response time. The problem of redundant calculations of common expressions in the target columns is even more pronounced in complex queries involving multiple table joins or subqueries.

[0003] In existing technologies, when a query contains multiple conditional branches connected by OR, a syntax tree is traversed to identify common expressions in each branch and extract them as subqueries or push them down to the base table. However, this optimization only targets OR expressions in the WHERE clause and cannot handle common expressions in the SELECT list (target column) or aggregate functions. For nested expressions, it cannot recursively extract multiple levels of common items. Furthermore, the lack of sufficient consideration of query context dependencies when extracting common expressions may lead to semantic errors.

[0004] Therefore, how to efficiently identify and extract common expressions from target columns or aggregate functions, and push them down to subqueries or intermediate results, has become a key issue in database query optimization. Summary of the Invention

[0005] This application provides a common expression optimization method, apparatus, device, storage medium, and program product to solve the technical problem of how to efficiently identify and extract common expressions in target columns or aggregate functions and push them down to subqueries or intermediate results.

[0006] Firstly, this application provides a common expression optimization method, including:

[0007] Receive the initial query statement and parse it into a query tree;

[0008] The target column expression and aggregate function expression in the query tree are recursively traversed, and the nodes and sub-items of each expression in the query tree are parsed to obtain the parsing result;

[0009] Based on the parsing results, the common expressions in the query tree are identified, and the reference positions of the common expressions in the query tree are recorded. The common expressions are used to characterize expressions that are repeatedly evaluated. The common expressions include expressions and aggregate functions.

[0010] Based on the reference position, a subquery node corresponding to the query tree is generated. The subquery node is then inserted into the query tree to replace the common expressions that are calculated repeatedly in the query tree, thus obtaining the target query statement. The subquery node contains the common expression.

[0011] In one possible embodiment, recursively traversing the target column expression and aggregate function expression in the query tree includes:

[0012] Perform a depth-first traversal of each expression node in the target column expression and aggregate function expression in the query tree, and recursively analyze the sub-items of each expression node until the atomic expression at the bottom level of the query tree is reached.

[0013] In one possible embodiment, based on the parsing results, common expressions in the query tree are identified, including:

[0014] Establish and maintain a set of common expressions, and store the identified sub-expressions and their reference positions in the query tree in the set;

[0015] If, during recursive traversal, the current subexpression is found to exist in the set of common expressions, the current expression is determined to be a common expression, and the parsing of the sub-items of the current subexpression is stopped.

[0016] In one possible embodiment, identifying common expressions in the query tree specifically includes:

[0017] Get the computational cost of the current subexpression;

[0018] Adjust the priority of common expressions based on computational cost to extract subexpressions according to priority.

[0019] In one possible embodiment, the method further includes:

[0020] In a distributed database environment, the computation results of public expressions whose computational cost exceeds a preset computational cost threshold are shared among all nodes in the distributed database environment.

[0021] In one possible embodiment, generating sub-query nodes corresponding to the query tree specifically includes at least one of the following:

[0022] Based on the multi-level nesting depth recognition mechanism, the level of nested expressions is dynamically identified, and the corresponding common expressions are extracted;

[0023] And / or, through a dynamic priority evaluation model, determine the extraction priority of common expressions and adjust the extraction order of common expressions;

[0024] And / or, in a distributed database environment, the computation results of common expressions are shared across nodes.

[0025] Secondly, this application provides a common expression optimization apparatus, comprising:

[0026] The query tree generation module is used to receive the initial query statement and parse the initial query statement into a query tree.

[0027] The expression recursive traversal module is used to recursively traverse the target column expression and aggregate function expression in the query tree, parse the node and sub-items of each expression in the query tree, and obtain the parsing result;

[0028] The common expression identification module is used to identify common expressions in the query tree based on the parsing results and record the reference position of the common expressions in the query tree. Common expressions are used to represent expressions that are repeatedly evaluated. Common expressions include expressions and aggregate functions.

[0029] The subquery generation and replacement module is used to generate subquery nodes corresponding to the query tree based on the reference position, insert the subquery nodes into the query tree to replace the common expressions that are calculated repeatedly in the query tree, and obtain the target query statement. The subquery nodes contain the common expressions.

[0030] Thirdly, this application provides an electronic device, including: a processor and a memory communicatively connected to the processor;

[0031] The memory stores instructions that the computer executes;

[0032] The processor executes computer-executable instructions stored in memory to implement any of the methods of the first aspect.

[0033] Fourthly, this application provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, are used to implement the method of any one of the first aspects.

[0034] Fifthly, this application provides a computer program product, including a computer program that, when executed by a processor, implements the method of any one of the first aspects.

[0035] The common expression optimization method, apparatus, device, storage medium, and program product provided in this application receive an initial query statement and parse it to form a query tree. They then recursively traverse and parse the target column expression and aggregate function expression in the query tree, identify common expressions in the query tree, record their reference positions in the query tree, and generate sub-query nodes containing the common expressions based on the reference positions. These sub-query nodes are then inserted into the query tree to replace the repetitive calculations of common expressions. This approach can more accurately detect and handle repetitive expressions in multi-layered nesting and complex calculation scenarios, thereby reducing the overhead of repetitive calculations during SQL execution, lowering query optimization complexity, and ensuring the semantic correctness of query results. Attached Figure Description

[0036] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.

[0037] Figure 1 A flowchart illustrating a common expression optimization method provided in an embodiment of this application;

[0038] Figure 2 A flowchart illustrating an optimization method for processing common expressions provided in an embodiment of this application;

[0039] Figure 3 This is a schematic diagram of a common expression optimization device provided in an embodiment of this application;

[0040] Figure 4 This is a schematic diagram of the structure of an electronic device provided in an embodiment of this application.

[0041] The accompanying drawings illustrate specific embodiments of this application, which will be described in more detail below. These drawings and descriptions are not intended to limit the scope of the concept in any way, but rather to illustrate the concept of this application to those skilled in the art through reference to particular embodiments. Detailed Implementation

[0042] Exemplary embodiments will now be described in detail, examples of which are illustrated in the accompanying drawings. When the following description relates to the drawings, unless otherwise indicated, the same numbers in different drawings represent the same or similar elements. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with this application. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this application as detailed in any of the foregoing embodiments.

[0043] It should be noted that the user information (including but not limited to user device information, user personal information, etc.) and data (including but not limited to data used for analysis, data stored, data displayed, etc.) involved in this application are all information and data authorized by the user or fully authorized by all parties. Furthermore, the collection, storage, use, processing, transmission, provision, disclosure, and application of the relevant data all comply with the relevant laws, regulations, and standards of the relevant countries and regions, have taken necessary confidentiality measures, do not violate public order and good morals, and provide corresponding operation access points for users to choose to authorize or refuse.

[0044] Furthermore, the technical solution involved in this application, which involves big data analysis of user information (including but not limited to personal biometrics, identity data, consumption data, asset data, electronic terminal operation data, etc.) and the use of artificial intelligence technology for automated decision-making, and makes decisions that have a significant impact on personal rights based on the results of automated decision-making, provides users with corresponding operation entry points for users to choose to agree to or reject the results of automated decision-making; if the user chooses to reject, the process will proceed to the expert decision-making process.

[0045] It should be noted that the common expression optimization method, apparatus, device, storage medium, and program product provided in this application can be used in the field of database query optimization, or in any field other than database query optimization. The application field of the common expression optimization method, apparatus, device, storage medium, and program product in this application is not limited.

[0046] Query optimization in database management systems falls under the field of data processing and query execution optimization technology, and is typically deployed in the parser, optimizer, and executor chain within the database kernel. When a business system submits an SQL statement, the database first converts the query statement into a query tree, and then performs expression analysis, cost evaluation, and query rewriting based on the query tree to support the execution of a large number of complex queries in scenarios such as online transaction processing, online analytical processing, and report statistics.

[0047] In the above scenarios, user-submitted queries often include target column calculations, aggregate function calculations, and multi-level nested expressions. Especially in statistical reports, business analysis, and multi-indicator summary tasks, the same sub-expression may appear repeatedly in multiple target columns or multiple aggregate items. Therefore, the ability to identify and process expressions during the query optimization stage directly affects the database's response performance and resource utilization.

[0048] Existing query optimization solutions typically reduce the overhead of repeated calculations during SQL execution through expression parsing, syntax tree analysis, and query rewriting. A common approach is to identify common items around the condition judgment part. After parsing the query tree, the same or similar expressions in specific condition branches are matched, and the identified common items are then used in subsequent execution through pushdown or rewriting to reduce some of the repeated evaluation processes.

[0049] However, this type of approach primarily focuses on conditional branch expressions, with insufficient coverage of repeated sub-expressions in the target column and aggregate functions. When a query contains multiple statistical indicators or multi-level nested operations, even if multiple expressions share the same calculation fragment, existing methods struggle to fully identify the corresponding relationships at the query tree level, leading to the same sub-expressions being repeatedly parsed and executed in different locations.

[0050] Furthermore, in complex nested scenarios, insufficient identification of common items can lead to inadequate query rewriting, resulting in increased CPU consumption and memory usage. It also makes it difficult for the optimizer to complete high-quality rewriting while ensuring the semantic correctness of the query, ultimately affecting the execution efficiency of complex queries and the system throughput.

[0051] In light of this, improving the identification and processing capabilities of common terms in target column expressions and aggregate function expressions during database query optimization has become a pressing technical problem. To address this issue, a common expression optimization method is proposed. Upon receiving the initial query statement, it is parsed into a query tree. The target column expressions and aggregate function expressions in the query tree are recursively traversed, parsing the nodes and sub-items of each expression. Based on the parsing results, common expressions are identified and their reference positions in the query tree are recorded. Subsequently, subquery nodes containing common expressions are generated based on these reference positions, and these subquery nodes are inserted into the query tree to replace repeatedly calculated common expressions. This reduces redundant calculations and maintains the correctness of the query semantics during the database optimizer's processing of the query tree.

[0052] The technical solution of this application and how the technical solution of this application solves the above-mentioned technical problems are described in detail below with specific embodiments. These specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments. The embodiments of this application will now be described with reference to the accompanying drawings.

[0053] Figure 1 This is a flowchart illustrating a common expression optimization method provided in an embodiment of this application, as shown below. Figure 1 As shown, the method includes:

[0054] S101: Receive the initial query statement and parse the initial query statement into a query tree.

[0055] In this step, the initial query statement is an SQL (Structured Query Language) statement submitted by the business system, client application, or database session interface to the database management system. The statement content must at least contain a list of SELECT statements to be analyzed, and may further contain one or more of the following structures: FROM, WHERE, GROUP BY, HAVING, and ORDER BY. The query tree is a tree structure used to carry the initial query statement. After completing lexical and syntactic parsing, the database kernel converts the statement into a hierarchical set of nodes. Different nodes represent projection items, function calls, arithmetic operations, field references, constants, aggregate calculations, and their parent-child dependencies, ensuring that subsequent traversal, identification of common expressions, and insertion of subquery nodes are all performed based on a unified internal representation. In this application, this step can be completed collaboratively by the parser and optimizer in the database kernel. Specifically, after receiving the initial query statement in text form, the parser first performs lexical segmentation and syntactic reduction on keywords, identifiers, operators, bracket levels, and function parameters, then generates an abstract syntactic representation, which is subsequently converted into a query tree structure that the optimizer can process. For target column expressions and aggregate function expressions, the parsing phase not only preserves the expression text but also establishes node types, data types, scope, input column sources, and alias mappings. This ensures that subsequent common expression recognition is based on structural equivalence rather than string literal equivalence. In one possible implementation, when the initial query statement is " When a query tree is executed, the parser generates a query tree containing two parent expression nodes. The first node corresponds to the target column expression "a+b", and the second node corresponds to the aggregate function expression "sum(a+b)". The second node then retains its child node structure for the parameter expression "a+b". If the statement contains nested expressions, such as " If a query tree is created, it will maintain "(a+b)" as a deeper child node, ensuring that common expressions can still be located in different higher-level expressions. To guarantee the semantic correctness of subsequent rewrites, column relationships, aggregation levels, and grouping semantics are annotated when parsing into a query tree. For example, it distinguishes between expressions at the ordinary projection level and those at the aggregation parameter level, differentiates the reference differences of columns with the same name under different table aliases, and records whether expressions cross aggregation boundaries. Based on the above analysis, by parsing the initial query statement into a query tree, subsequent processing no longer matches linear SQL text character by character, but analyzes the node structure with parent-child relationships and semantic attributes, thus enabling the stable extraction of repetitive calculation fragments within a unified structure. It should be understood that the above example is for demonstration purposes only and is not a limitation.

[0056] S102: Recursively traverse the target column expression and aggregate function expression in the query tree, parse each expression node and sub-item in the query tree, and obtain the parsing result.

[0057] In this step, the target column expression is the expression in the SELECT list of the SQL query, which is one of the key objects for recursive traversal and extraction of common expressions. The aggregate function expression is an expression containing sum (Sum), average (Average), count, max, min, or equivalent aggregate operators, which also needs to be recursively traversed and identified as a common expression. The parsing result is a structured record formed for each expression node and its sub-items, including at least the node type, operator type, child node order, operand content, expression level, whether it is inside an aggregate function, the identifier of the target item, and the path information of the node in the query tree. In this application, after obtaining the query tree, the optimizer extracts the root expression nodes corresponding to all SELECT lists from the query tree, and simultaneously extracts the aggregate function nodes and their parameter expression nodes, then uses a recursive approach to explore layer by layer. Specifically, recursive traversal can be performed on each candidate expression: when an arithmetic operation node is accessed, its left and right operands are traversed; when a function call node is accessed, each parameter node in the parameter list is traversed; when a field reference node or constant node is accessed, it is written as a leaf node into the parsing result. For deeply nested expressions, the recursive process continues until all sub-items are parsed. To support subsequent structure comparison, a normalized expression description is generated for each node during traversal. Normalization may include removing irrelevant format differences, standardizing function name representations, preserving computational precedence indicated by parentheses, marking unary and binary operation types, and constructing stable sorted sub-item representations for commutative operations when necessary. Simultaneously, the relationships between nodes and their parent and ancestor nodes are recorded to indicate which target column expression or aggregate function expression a given sub-expression is located within. For example, for the expression " "and" After recursively traversing, it will parse out "price", "qty", and " “tax” Different levels of nodes, and save them in the parsing results. The paths are located inside the aggregation parameters and the target column expression, respectively. For expressions containing multiple levels of nested functions, such as "round(sum(a+b),2)", the recursive process first identifies the outermost round function node, then enters the sum function node, then the "a+b" node, and finally generates a complete parent-child hierarchical link. The parsing results formed in this step can be organized into a node description table, an expression signature table, and a path index table. The node description table records the basic attributes of the nodes, the expression signature table records the normalized structural representation, and the path index table records the actual position of each node in the query tree. Based on the above analysis, it can be seen that after recursively traversing and parsing each expression node and its sub-items, the repeated calculation fragments contained in the target column expression and aggregation function expression in the query tree are decomposed into comparable structural units, thus providing a basis for subsequent identification of the same sub-expression at different positions. In complex nested scenarios, this step directly determines the completeness of the identification of common expressions, because comparing only on the top-level expression cannot cover deep sub-expressions, while layer-by-layer recursion can separate repeated fragments from the outer wrapping structure. It should be understood that the above example is only for demonstration and not a limitation.

[0058] S103: Based on the parsing results, identify the common expressions in the query tree and record the reference positions of the common expressions in the query tree.

[0059] In the embodiments of this application, a common expression is used to characterize an expression that is repeatedly calculated. The common expression includes an expression and an aggregation function.

[0060] In this step, the common expression is the expression that appears repeatedly in multiple positions as determined by the parsing results. It can appear between multiple target column expressions, simultaneously between target column expressions and aggregate function expressions, or within multiple aggregate function expressions. The reference position records the location of the common expression in the query tree, including at least the corresponding node identifier, parent node identifier, the root node identifier of the expression it belongs to, the context information of whether it is in the target list or aggregate parameters, and the hierarchical path in the original expression. In this application, after obtaining the parsing results in S102, the optimizer performs a merge comparison of the parsed structured expression signatures, which can be performed using a combination of hash indexing and structural equivalence verification. First, an expression signature is generated for each non-leaf expression node. The signature can be obtained by concatenating the node type, operator, normalized sub-item signature, and necessary semantic tags. Then, nodes with the same signature are grouped into the same candidate set. Next, structural equivalence verification is performed on the nodes in the candidate set to exclude cases where there is only a hash collision but different structures. If the expression node corresponding to the same signature appears twice or more in the query tree, it is identified as a common expression, and a mapping relationship is established between this common expression and multiple reference locations. To maintain the correctness of query semantics, scope and semantic consistency constraints are also set for common expressions during the identification process. For example, when two expressions with the same structure are located in different query blocks, different grouping levels, or different related subquery contexts, they are not directly merged into the same common expression; when an expression contains non-deterministic functions, session-related functions, or calculations that depend on external state, it is removed from the common expression candidate; when the columns referenced by an expression have the same name but come from different table aliases or different join branches, they are not considered the same reusable expression. For example, for " In the parsed results, "a+b" appears in the target column expression, the sum parameter expression, and the max parameter expression. After structural equivalence and semantic consistency checks, it can be identified as the same common expression, and three reference positions are recorded respectively, including its position under the root node of the first projection item, its position under the parameter path of the sum node, and its position under the parameter path of the max node. For example, " It can recognize "a+b" as a common expression, but will not recognize " "and" "Error merging. This step involves matching each parsed result and establishing a mapping from common expressions to their reference locations, enabling the optimizer to obtain the replacement basis needed for subsequent rewriting. Based on the above analysis, it can be seen that common expression identification does not only determine text duplication, but also identifies duplicate calculation segments with consistent expression structure, computational semantics, and scope at the query tree level. Therefore, it can cover deep duplicates in target column expressions and aggregate function expressions, and provide precise location information for unified rewriting in complex queries. It should be understood that the above example is only for demonstration and not a limitation."

[0061] S104: Based on the reference position, generate the subquery node corresponding to the query tree, insert the subquery node into the query tree to replace the common expressions that are calculated repeatedly in the query tree, and obtain the target query statement.

[0062] In this embodiment of the application, the subquery node contains a common expression.

[0063] In this step, a subquery node is a node structure used to contain the calculation logic of a common expression and is attached to an appropriate level in the query tree. Internally, it includes at least the common expression itself, the output column identifier corresponding to the common expression, and the set of input columns required to carry the calculation of the common expression. The target query statement is a semantically equivalent SQL statement derived after replacement and reorganization in the query tree. During execution, the output results of the subquery node are reused to replace the original multiple repetitive calculations. In this application, the optimizer first determines the minimum common carrying level of each common expression based on the reference position recorded in S103. If multiple reference positions belong to the same query block and share the same range of input columns, a subquery node is generated within that query block, the common expression is promoted to the output list of the subquery node, and an internal alias is assigned to it, such as "ce_1". Subsequently, the common expression nodes at each reference position in the original query tree are replaced with column reference nodes for "ce_1". For scenarios involving aggregate function parameters, the subquery node is placed in the projection layer before the aggregate calculation, so that the common expression is first calculated at the basic row level, and then the calculation result is referenced by the upper-level aggregate node. For example, the original query statement is " "When rewriting, subquery nodes can be constructed on top of the FROM object." The outer query tree is rewritten as "SELECT ce_1, sum(ce_1) FROM subquery GROUP BY". "a,b,ce_1" or an internal representation equivalent to the original grouping semantics. For scenarios where the common expression appears in multiple target column expressions, the subquery node can output the common expression once, and multiple upper-level projection items can repeatedly reference the same output column. When generating a subquery node, it is necessary to synchronously supplement the base columns, grouping columns, and join columns required for the subquery to maintain the upper-level semantics, preventing the upper-level node from losing its input source after replacement; if the common expression depends on a specific set of columns in the original query, then that set of columns is included in the subquery's output or input relationship. After inserting the subquery node, the optimizer rebinds the column reference relationship, updates the parent-child pointers, output column indices, alias resolution mappings, and type inference results in the query tree, and performs a validity check on the replaced query tree to confirm that the replacement of the common expression does not change the aggregation boundary, null value propagation rules, and expression evaluation order. After completing the above processing, the database kernel regenerates the target query statement based on the rewritten query tree, or directly hands the query tree over to the subsequent cost optimization and execution plan generation modules for further processing. For example, in " In the context of querying, you can first generate the query in the subquery node. Then rewrite the outer expression as " ";exist" In the context of "", "can be calculated in the subquery node". The outer layers execute "sum(ce_1)" and "avg(ce_1)" respectively. Based on the above analysis, it can be seen that by generating subquery nodes carrying common expressions based on the reference position, and uniformly replacing multiple repeated subexpressions in the query tree with references to the output columns of the subqueries, the query optimizer can converge the repeated evaluations originally scattered in the target column expression and aggregate function expression into a single calculation while maintaining the consistency of query semantics. In this way, in subsequent execution stages, the same subexpression will no longer be repeatedly expanded in multiple projection terms or multiple aggregate terms, the rewriting integrity of the query tree is improved, and the repeated calculation paths in complex nested queries are eliminated. It should be understood that the above example is only for demonstration and is not a limitation.

[0064] In one implementation scenario, Figure 2 A flowchart illustrating an optimization method for processing common expressions provided in this application embodiment is shown below. Figure 2 As shown, optimization methods for processing common expressions may include:

[0065] The initial query's target column is processed, and common items are collected. Specifically, this includes: traversing the target column of the plan, determining if it's a single column or a constant; if the target column is a single column or a constant, returning and generating a new target column based on the common linked list; if the target column is neither a single column nor a constant, determining if it's in the collected linked list; if it is, collecting the node and recursively working to its child nodes; if it's not in the collected linked list, returning and generating a new target column based on the common linked list. The original plan is pushed down to the left of the new plan, and the new plan tree is returned. The user then uses the new plan tree to perform a query to obtain the query results corresponding to the initial query.

[0066] For example, an optimization method for processing common expressions may include: 1. Traversing each node and processing all expressions of that node.

[0067] 2. Recursively process each sub-item of a single expression, such as Recursively starting from sum: .

[0068] Determine if expression sub-items have been collected: (1) If not collected, recursively collect sub-items; (2) If collected, increment the expression reference by one, exit, and do not recursively collect sub-items, such as... If it is a common item, it will not be recursively called to (1-b1).

[0069] 3. If there are duplicate sub-items, create a new Subquery node and iterate through and copy the original node: (1) Generate the target column of the current node based on the collected common expression nodes and other non-repeating expressions. The target column is (2) Construct a subquery node. The lower-level node of the subquery node is the node in (1), modified as follows: Based on the expression node recursively reached, determine its position in the lower level. It is the first target column in the lower level, denoted by com1. (1+c1) is the second target column in the lower level, replaced by col1. In the current level query, the target columns of the lower level subquery are com1 and col1; the target columns of the current level are determined by... It becomes sum(com1), sum(com1) (col1). Process the expression of each node, traverse each node that stores the expression, extract common expressions to reduce the calculation of repeated expressions. Perform a query based on the optimized query statement to obtain the query results.

[0070] Scenario 1: Common term extraction based on aggregation functions:

[0071] ;

[0072] =》select sum(com1), sum(com1 c1) from (select a1 (1 - b1) ascom1, 1 + c1 as c1 from t1);

[0073] The aggregate function has two expressions, namely a1 (1-b1), a1 (1-b1) (1+c1), a1 (1-b1) is a common term of the two functions. Extract the common expression and move the common term down.

[0074] Scenario 2: Extracting common items based on the target column:

[0075] select a1 + 1 as add1, a1 + 1 + 2 as add3, (a1 + 1) 2 (a1 + 1) asa3 from t1, t2 where a1 = a2;

[0076] => select com1 as add1, com1 + 2 as add3, com1 2 com1 as a3 from(select a1 + 1 as com1 from t1, t2 where a1 = a2) v;

[0077] The target columns all have a common item a1 + 1. Extract this common item and push it down.

[0078] In another implementation scenario, the common expression optimization method is applied to the OLAP (Online Analytical Processing) scenario of a database management system (DBMS). Users frequently execute queries containing complex expressions, aggregate functions, or target columns. These queries may contain multi-level nested expressions, multiple aggregate functions (SUM, AVG, or target columns from a SELECT list). The user submits the initial query statement. Next, the initial query statement is received and parsed into a query tree. After the database optimizer completes the query tree construction, it starts processing the target column and aggregate function expressions in the query tree. Starting from the root node SELECT, it performs a depth-first traversal on each expression node, recursively analyzing the sub-items of each expression node, and continues to expand downwards until it reaches the atomic expressions at the bottom layer of the query tree.

[0079] During the traversal, the code is parsed sequentially. Recursive analysis of subexpressions And 1+c1, and generate a parsing result for each expression node and its sub-items. The parsing result includes the expression structure, the composition relationship of sub-expressions, and the position of the expression in the query tree. For The resulting syntax tree structure is Following a1 and 1-b1; for The resulting syntax tree structure is Next ,in Next And 1+c1, and Following a1 and 1-b1. Recording synchronously during the parsing process. The corresponding reference position in the query tree.

[0080] During the recursive traversal, a common expression set is established and maintained, storing the identified sub-expressions and their reference positions in the query tree. The computational cost of each sub-expression involved in the identification is obtained, and the priority of the common expressions is adjusted based on the computational cost. This ensures that sub-expressions with higher computational cost or higher reuse value have a corresponding priority order during extraction. Simultaneously, a multi-level nesting depth identification mechanism dynamically identifies the nesting level of expressions, extracting corresponding common expressions at different nesting levels, and adjusting the extraction order of common expressions through a dynamic priority evaluation model. During the first traversal... At that time, first judge If it already exists in the set of public expressions, and if not, continue recursively analyzing its sub-items a1 and 1-b1, and then... The referenced position is written into the public expression set; when iterating to... Internal If the current subexpression is found to already exist in the common expression set, then the current subexpression is identified as a common expression, its reference position in the query tree is recorded, and further parsing of the current subexpression's sub-items is stopped. Analysis of a1 and 1-b1 is no longer performed, thus generating the common expression set { }

[0081] After identifying common expressions and recording their reference positions, sub-query nodes are generated based on each reference position to form a query tree. These sub-query nodes contain the corresponding common expressions, and are then inserted into the query tree to replace any duplicate common expressions within the tree. Position to construct subquery nodes , where the common expression The expression 1+c1 is extracted as com1, and the expression 1+c1 is retained as col1. The original expression is then rewritten, with SUM( Replace ) with SUM(com1), and Replace with SUM(com1) col1), and verify the semantic equivalence between the subquery and the original query. The subquery node structure corresponding to the common expression is retained in the query tree to obtain the target query statement SELECT SUM(com1), SUM(com1) col1) FROM ( SELECT a1 (1-b1) AS com1, 1+c1 AS col1 FROM t1) AS subquery;

[0082] In a distributed database environment, for common expressions whose computational cost exceeds a preset threshold, the computation result corresponding to the common expression is shared across all nodes in the distributed database environment. During the generation of subquery nodes and the rewriting of the query tree, the common expressions are uniformly replaced using the shared computation results across nodes, and the subquery node structure corresponding to the common expressions is preserved in the query tree. When executing the optimized query, the subquery SELECT a1 is executed first. (1-b1) AS com1,1+c1 AS col1 FROM t1, calculate the values ​​of com1 and col1, then directly reference com1 and col1 in the outer query to calculate SUM(com1) and SUM(com1) col1), where a1 (1-b1) in SUM(a1) (1-b1)) and SUM(a1) (1-b1) In (1+c1)), the common term is calculated only once.

[0083] The common expression optimization method provided in this embodiment includes: receiving an initial query statement and parsing it into a query tree; recursively traversing the target column expression and aggregate function expression in the query tree and parsing nodes and sub-items; identifying common expressions based on the parsing results and recording their reference positions; generating sub-query nodes containing common expressions based on the reference positions and inserting them into the query tree to complete the replacement; and finally obtaining the target query statement. In this application, by expanding the scope of common expression identification from conditional branches to target column expressions and aggregate function expressions, and combining structured traversal of the query tree, structural equivalence identification, and position-based subquery rewriting, repetitive calculation fragments in complex queries are uniformly extracted and reused. This enables the database optimizer to fully process repetitive sub-expressions in scenarios involving multi-indicator statistics, report summaries, and multi-level nested operations. The target query statement reduces repeated evaluation paths while maintaining semantic consistency and directly supports computational reuse in the subsequent execution plan generation process. It should be understood that the above examples are merely illustrative and not limiting.

[0084] Based on the aforementioned embodiments, a further recursive traversal is performed on the target column expression and aggregate function expression in the query tree, including: performing a depth-first traversal on each expression node in the target column expression and aggregate function expression in the query tree, and recursively analyzing the sub-items of each expression node until the atomic expression at the bottom level in the query tree is reached.

[0085] In its implementation, after parsing the initial query statement and generating the query tree, the database optimizer traverses the expression tree located within the target list and aggregate list of the query tree. Expression nodes can consist of column references, constants, arithmetic operations, function calls, and aggregate function calls. When a node corresponds to a function call, its parameter list is further parsed; when a node corresponds to an operational expression, its left and right child nodes are parsed, thus forming a top-down recursive expansion process. For multi-level nested expressions, the system drills down continuously in the order of visiting the parent node first, then the child nodes, until it encounters a field name, a numerical constant, or other nodes that cannot be further decomposed, and records each level of nodes and their containment relationships as the parsing result.

[0086] During this parsing process, the system can simultaneously save the current node's position in the query tree and its hierarchical relationship with its parent nodes. This allows for subsequent identification phases to determine whether there are identical computational fragments between different target column expressions and aggregate function expressions. By fully covering all relevant expression nodes, nested calculations, duplicate parameters, and composite aggregate terms in the query tree can be expanded layer by layer and incorporated into a unified analysis scope. This provides a foundation for identifying common expressions, recording reference positions, and generating replacement subquery nodes.

[0087] By employing the recursive traversal method described above, the query optimizer can fully acquire the structural information of the target column expression and aggregate function expression, and accurately locate the underlying atomic expressions and their combination relationships, ensuring that common subexpressions can still be stably identified even in complex nested scenarios. This reduces the computational overhead caused by repeated parsing and allows subsequent query rewriting to be built upon the complete expression tree information, thereby improving the processing efficiency and rewriting accuracy of complex queries.

[0088] Based on the aforementioned embodiments, further, according to the parsing results, the common expressions in the query tree are identified, including: establishing and maintaining a set of common expressions, storing the identified sub-expressions and their reference positions in the query tree in the set; if the current sub-expression is found to exist in the set of common expressions during recursive traversal, the current expression is determined to be a common expression, and the parsing of the sub-items of the current sub-expression is stopped.

[0089] In its implementation, after completing a depth-first recursive traversal of the query tree, the database optimizer writes the subexpressions extracted during the traversal and their corresponding node positions into a set of common expressions. When a new subexpression is encountered in subsequent traversals, it performs structural and semantic matching between the current subexpression and the expressions already stored in the set. If the matching result indicates that the current subexpression already exists in the set, it is marked as a common expression, and its sub-items are no longer parsed further. This allows the subexpression to be used as a whole in subsequent processing for reference position recording and subquery node generation.

[0090] In one implementation, the set of common expressions can be implemented using a hash table, a balanced tree, or a key-value mapping structure. The expression itself serves as the key, and the reference position is the corresponding storage content. When the same subexpression appears in different positions, multiple reference positions can be merged into the same record. This structure facilitates fast lookup, insertion, and update during recursive traversal, and terminates further traversal of its internal nodes upon identifying duplicate expressions. In practical applications, other data structures can also be chosen for this set, and this application does not impose any limitations on them.

[0091] By establishing and maintaining a set of common expressions, and immediately confirming that a subexpression already exists in the set as a common expression and stopping the parsing of the sub-item, duplicate calculation segments in the query tree can be identified in a timely manner and complete reference information can be preserved. This provides an accurate basis for generating subquery nodes based on the reference position, while reducing the overhead of re-analyzing duplicate subtrees and ensuring that the common expression identification results are consistent with the query tree structure.

[0092] In one possible implementation, identifying common expressions in the query tree specifically includes: obtaining the computational cost of the current subexpression; and adjusting the priority of common expressions based on the computational cost to extract subexpressions according to their priority.

[0093] In practical implementation, after obtaining the current subexpression during query tree traversal, the optimizer first generates a corresponding computational cost value for the subexpression, then compares this cost value with the cost values ​​of other recorded common expressions, and updates the sorting field in the common expression set based on the comparison result, so that the expressions to be processed are extracted one by one according to the adjusted priority. For subexpressions with high cost and frequent repeated references, their priority can be set to a higher level so that common expression nodes are formed first; for subexpressions with low cost, extraction can be delayed to avoid generating low-yield subquery structures too early. In practical applications, the priority of common expressions can also be dynamically updated according to the expression structure of different query trees, which is not limited in this application.

[0094] Once the priority adjustment is complete, the optimizer selects the target sub-expression from the set of common expressions based on the current priority and outputs the information of the common expressions to be rewritten for use in the subsequent generation of subquery nodes. This process allows common expressions in the query tree to be extracted in descending order of computational cost, thus prioritizing expressions with higher repetitive computation costs to enter the rewriting process and replacing multiple repeated evaluations with a single calculation result in subsequent query execution.

[0095] By adopting the above approach, the query optimizer can sort common expressions based on their computational overhead, making the extraction process more consistent with the actual computational load distribution. This reduces the resources consumed by repeated parsing and computation, and improves the consistency and execution efficiency of complex query rewriting.

[0096] In one possible implementation, the method further includes: in a distributed database environment, sharing the computation results corresponding to public expressions whose computational cost exceeds a preset computational cost threshold to each node in the distributed database environment.

[0097] In this implementation, after the query optimizer identifies a common expression, it estimates its computational cost based on the query tree or execution plan. This estimate can be obtained by combining operator depth, nesting level, number of columns involved in the computation, and aggregation computation complexity. If the estimated computational cost is greater than a preset computational cost threshold, the computation result corresponding to the common expression is first obtained by one of the participating nodes and written into a shared result area accessible between nodes, or synchronized to other execution nodes by distributing messages, so that other nodes can directly read the result when processing the same common expression later, without repeating the same computation.

[0098] In one implementation, the shared result area can be located in a distributed cache, a result table maintained by a coordinating node, or an intermediate result storage unit with broadcast capabilities. Upon receiving the shared identifier, each node matches and reads the result based on the identifier, version, and validity information of the common expression, thereby obtaining an intermediate result consistent with its local computation. If the result size corresponding to the common expression is small, direct broadcasting can be used; if the result size is large, only the result reference address or index information can be shared to reduce cross-node transmission overhead. This sharing mechanism enables computationally expensive common expressions to reuse the same computation result across multiple nodes.

[0099] By sharing the computation results of a common expression in a distributed database environment when the computation cost exceeds a threshold, each node can directly reuse the generated intermediate results and reduce the number of repeated evaluations when executing sharded or parallel operators for the same type of query. This reduces redundant computation and communication overhead between nodes and improves the execution efficiency and resource utilization of complex queries in a distributed scenario.

[0100] In one possible implementation, generating subquery nodes corresponding to the query tree specifically includes at least one of the following: dynamically identifying the level of nested expressions based on a multi-level nesting depth recognition mechanism and extracting the corresponding common expressions; and / or determining the extraction priority of common expressions and adjusting the extraction order of common expressions through a dynamic priority evaluation model; and / or sharing the calculation results of common expressions across nodes in a distributed database environment.

[0101] In its implementation, after receiving the query tree, the database optimizer builds an expression stack for the target column expression and aggregate function expression, and synchronously writes the current depth value and parent-child dependencies during recursive traversal. When a subexpression is detected to appear repeatedly in multiple positions and is in a relatively inner nested structure, the system generates corresponding common expression candidates based on the depth marker and constructs subquery nodes accordingly. For cases where multiple candidate common expressions coexist, the optimizer calls a dynamic priority evaluation model, sorting the candidates based on computational cost and reuse frequency. It first generates subquery nodes corresponding to high-priority items, then generates the remaining nodes, thus forming a rewrite result consistent with the query tree hierarchy. In distributed execution scenarios, the common expression results calculated by the subquery nodes can be written to a shared cache between nodes or broadcast to other nodes via a distribution channel. Subsequent nodes directly read and reference this result when executing related expressions.

[0102] This approach considers nesting levels, extraction order, and node sharing relationships when rewriting the query tree, enabling common expressions to be accurately located hierarchically and extracted in an ordered manner according to priority. It also allows for the reuse of computed results in a distributed environment. This reduces the number of repeated evaluations, lowers the computational overhead of the optimizer and executor, and improves the execution efficiency and resource utilization of complex queries in single-machine or distributed databases.

[0103] Figure 3 This is a schematic diagram of a common expression optimization device provided in an embodiment of this application, as shown below. Figure 3 As shown, the common expression optimization device 30 provided in this embodiment includes:

[0104] The query tree generation module 301 is used to receive the initial query statement and parse the initial query statement into a query tree.

[0105] The expression recursive traversal module 302 is used to recursively traverse the target column expression and aggregate function expression in the query tree, parse the node and sub-item of each expression in the query tree, and obtain the parsing result;

[0106] The common expression identification module 303 is used to identify the common expressions in the query tree based on the parsing results and record the reference position of the common expressions in the query tree. The common expressions are used to represent expressions that are repeatedly calculated. The common expressions include expressions and aggregate functions.

[0107] The subquery generation and replacement module 304 is used to generate subquery nodes corresponding to the query tree based on the reference position, insert the subquery nodes into the query tree to replace the common expressions that are calculated repeatedly in the query tree, and obtain the target query statement. The subquery nodes contain the common expressions.

[0108] In one possible implementation, the expression recursive traversal module 302 is specifically used to: perform a depth-first traversal of each expression node in the target column expression and aggregate function expression in the query tree, and recursively analyze the sub-items of each expression node until the atomic expression at the bottom level in the query tree is reached.

[0109] In one possible implementation, the common expression identification module 303 is specifically used to: establish and maintain a set of common expressions, store the identified sub-expressions and their reference positions in the query tree in the set; and, if the current sub-expression is found to exist in the set of common expressions during recursive traversal, determine that the current expression is a common expression and stop parsing the sub-items of the current sub-expression.

[0110] In one possible implementation, the common expression identification module 303 is further specifically used to: obtain the computational cost of the current sub-expression; and adjust the priority of the common expression according to the computational cost, so as to extract the sub-expression according to the priority.

[0111] In one possible implementation, the common expression optimization device is further specifically used to: in a distributed database environment, share the calculation results corresponding to common expressions whose computational cost exceeds a preset computational cost threshold to each node in the distributed database environment.

[0112] In one possible implementation, the subquery generation and replacement module 304 is specifically used to: dynamically identify the level of nested expressions based on a multi-level nesting depth identification mechanism and extract the corresponding common expressions; and / or, determine the extraction priority of common expressions and adjust the extraction order of common expressions through a dynamic priority evaluation model; and / or, in a distributed database environment, share the calculation results of common expressions across nodes.

[0113] The common expression optimization device provided in this embodiment can execute the method provided in the above method embodiment. Its implementation principle and technical effect are similar, and will not be described in detail here.

[0114] Figure 4 This is a schematic diagram of the structure of an electronic device provided in an embodiment of this application. Figure 4 As shown, the electronic device 40 may include a memory 401 and a processor 402. Optionally, the electronic device may also include a transceiver 403, wherein the memory 401 and the processor 402 communicate with each other; for example, the memory 401, the processor 402 and the transceiver 403 may communicate via a communication bus 404, the memory 401 is used to store a computer program, and the processor 402 executes the computer program to implement the method of the above embodiments.

[0115] Optionally, the aforementioned processor can be a Central Processing Unit (CPU), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), etc. The general-purpose processor can be a microprocessor or any conventional processor. The steps in the method embodiments disclosed in this application can be directly implemented by a hardware processor, or implemented by a combination of hardware and software modules within the processor.

[0116] This application also provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, implement the methods in any of the above method embodiments.

[0117] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the methods in any of the above method embodiments.

[0118] All or part of the steps in the above method embodiments can be implemented by hardware related to program instructions. The aforementioned program can be stored in a readable memory. When the program is executed, it performs the steps of the above method embodiments; and the aforementioned memory (storage medium) includes: read-only memory (ROM), RAM, flash memory, hard disk, solid-state drive, magnetic tape, floppy disk, optical disk, and any combination thereof.

[0119] This application describes embodiments with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It should be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processing unit of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processing unit of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart illustrations. Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.

[0120] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.

[0121] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1The steps of the function specified in one or more boxes.

[0122] Obviously, those skilled in the art can make various modifications and variations to the embodiments of this application without departing from the spirit and scope of this application. Therefore, if these modifications and variations to the embodiments of this application fall within the scope of this application and its equivalents, this application also intends to include these modifications and variations.

[0123] In this application, the term "comprising" and its variations can refer to non-limiting inclusion; the term "or" and its variations can refer to "and / or". The terms "first", "second", etc., in this application are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. In this application, "multiple" refers to two or more. "And / or" describes the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent: A existing alone, A and B existing simultaneously, and B existing alone. The character " / " generally indicates that the preceding and following related objects have an "or" relationship.

[0124] It should be noted that, for the sake of simplicity, the foregoing method embodiments are all described as a series of actions. However, those skilled in the art should understand that this application is not limited to the described order of actions, as some steps may be performed in other orders or simultaneously according to this application. Furthermore, those skilled in the art should also understand that the embodiments described in the specification are all optional embodiments, and the actions and modules involved are not necessarily essential to this application.

[0125] It should be further noted that although the steps in the flowchart are shown sequentially according to the arrows, these steps are not necessarily executed in the order indicated by the arrows. Unless explicitly stated herein, there is no strict order restriction on the execution of these steps, and they can be executed in other orders. Moreover, at least some steps in the flowchart may include multiple sub-steps or multiple stages. These sub-steps or stages are not necessarily completed at the same time, but can be executed at different times. The execution order of these sub-steps or stages is not necessarily sequential, but can be performed alternately or in turn with other steps or at least some of the sub-steps or stages of other steps.

[0126] It should be understood that the above-described device embodiments are merely illustrative, and the device of this application can also be implemented in other ways. For example, the division of units / modules in the above embodiments is only a logical functional division, and there may be other division methods in actual implementation. For example, multiple units, modules, or components may be combined, or integrated into another system, or some features may be ignored or not executed.

[0127] Furthermore, unless otherwise specified, the functional units / modules in the various embodiments of this application can be integrated into one unit / module, or each unit / module can exist physically separately, or two or more units / modules can be integrated together. The integrated units / modules described above can be implemented in hardware or as software program modules.

[0128] When integrated units / modules are implemented in hardware, the hardware can be digital circuits, analog circuits, etc. The physical implementation of the hardware structure includes, but is not limited to, transistors, memristors, etc. Unless otherwise specified, the processor can be any suitable hardware processor, such as a CPU, GPU, FPGA, DSP, and ASIC, etc. Unless otherwise specified, the storage unit can be any suitable magnetic or magneto-optical storage medium, such as Resistive Random Access Memory (RRAM), Dynamic Random Access Memory (DRAM), Static Random Access Memory (SRAM), Enhanced Dynamic Random Access Memory (EDRAM), High-Bandwidth Memory (HBM), Hybrid Memory Cube (HMC), etc.

[0129] If the integrated unit / module is implemented as a software program module and sold or used as an independent product, it can be stored in a computer-readable storage device (CMD). Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a memory and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods of the various embodiments of this application. The aforementioned memory includes various media capable of storing program code, such as a USB flash drive, read-only memory (ROM), random access memory (RAM), portable hard drive, magnetic disk, or optical disk.

[0130] In the above embodiments, the descriptions of each embodiment have their own emphasis. For parts not described in detail in a certain embodiment, please refer to the relevant descriptions of other embodiments. The technical features of the above embodiments can be combined arbitrarily. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as the combination of these technical features does not contradict each other, it should be considered within the scope of this specification.

[0131] Other embodiments of this application will readily occur to those skilled in the art upon consideration of the specification and practice of the invention disclosed herein. This application is intended to cover any variations, uses, or adaptations of this application that follow the general principles of this application and include common knowledge or customary techniques in the art not disclosed herein.

[0132] It should be understood that this application is not limited to the precise structure described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope.

Claims

1. A common expression optimization method, characterized in that, The method includes: Receive the initial query statement and parse the initial query statement into a query tree; The target column expression and aggregate function expression in the query tree are recursively traversed, and the nodes and sub-items of each expression in the query tree are parsed to obtain the parsing result; Based on the parsing results, the common expressions in the query tree are identified, and the reference positions of the common expressions in the query tree are recorded. The common expressions are used to characterize expressions that are repeatedly calculated, and the common expressions include expressions and aggregate functions. Based on the reference position, a sub-query node corresponding to the query tree is generated, and the sub-query node is inserted into the query tree to replace the common expressions that are calculated repeatedly in the query tree, thereby obtaining the target query statement. The sub-query node contains the common expression.

2. The method according to claim 1, characterized in that, The recursive traversal of the target column expression and aggregate function expression in the query tree includes: A depth-first traversal is performed on each expression node in the target column expression and the aggregate function expression in the query tree, and the sub-items of each expression node are recursively analyzed until the atomic expression at the bottom level in the query tree is reached.

3. The method according to claim 2, characterized in that, The step of identifying the common expressions in the query tree based on the parsing results includes: Establish and maintain a set of the public expressions, and store the identified sub-expressions and their reference positions in the query tree in the set; If, during recursive traversal, the current subexpression is found to exist in the set of common expressions, the current expression is determined to be a common expression, and the parsing of the sub-items of the current subexpression is stopped.

4. The method according to claim 3, characterized in that, The identification of common expressions in the query tree specifically includes: Get the computational cost of the current subexpression; The priority of the common expression is adjusted based on the computational cost, so that the sub-expression is extracted according to the priority.

5. The method according to claim 4, characterized in that, The method further includes: In a distributed database environment, the calculation results corresponding to public expressions whose computational cost exceeds a preset computational cost threshold are shared among the nodes in the distributed database environment.

6. The method according to claim 5, characterized in that, The generation of the sub-query node corresponding to the query tree specifically includes at least one of the following: Based on the multi-level nesting depth recognition mechanism, the level of nested expressions is dynamically identified, and the corresponding common expressions are extracted; And / or, by using a dynamic priority evaluation model, determine the extraction priority of the common expressions and adjust the extraction order of the common expressions; And / or, in the distributed database environment, the computation results of the public expression are shared across nodes.

7. A common expression optimization device, characterized in that, The device includes: The query tree generation module is used to receive an initial query statement and parse the initial query statement into a query tree. The expression recursive traversal module is used to recursively traverse the target column expression and aggregate function expression in the query tree, parse the node and sub-item of each expression in the query tree, and obtain the parsing result; The common expression identification module is used to identify the common expressions in the query tree based on the parsing results, and record the reference position of the common expressions in the query tree. The common expressions are used to characterize expressions that are repeatedly calculated, and the common expressions include expressions and aggregate functions. The subquery generation and replacement module is used to generate a subquery node corresponding to the query tree based on the reference position, insert the subquery node into the query tree to replace the common expressions that are calculated repeatedly in the query tree, and obtain the target query statement. The subquery node contains the common expression.

8. An electronic device, characterized in that, include: A processor, and a memory communicatively connected to the processor; The memory stores computer-executed instructions; The processor executes computer execution instructions stored in the memory to implement the method as described in any one of claims 1 to 6.

9. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer-executable instructions, which, when executed by a processor, are used to implement the method as described in any one of claims 1 to 6.

10. A computer program product, characterized in that, Includes a computer program that, when executed by a processor, implements the method of any one of claims 1 to 6.