Multi-table association SQL generation method based on graph structure reasoning
By using a graph-based reasoning-based method for generating SQL for multi-table joins, the problems of high error rate in path reasoning and insufficient semantic understanding in the generation of SQL for multi-table joins in vertical domains are solved. This method achieves logically complete and semantically consistent SQL generation, improving query efficiency and accuracy.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- BEIJING INST OF COMP TECH & APPL
- Filing Date
- 2025-12-18
- Publication Date
- 2026-04-21
AI Technical Summary
Existing natural language query technologies are applicable to single-table scenarios, but in the generation of SQL for multi-table joins in vertical domains, they suffer from problems such as high path reasoning error rate, insufficient semantic understanding, and difficulty in balancing SQL generation efficiency and correctness.
A multi-table SQL generation method based on graph structure reasoning is adopted. Through double-alignment modeling at the encoding end, graph structure reasoning and semantic constraint path reasoning, and efficient generation and structural constraints at the decoding end, the collaborative modeling and semantic matching of natural language and database structure are achieved, generating logically complete and semantically consistent SQL statements.
It improves semantic understanding and path reasoning accuracy in multi-table join scenarios, enhances SQL generation efficiency and execution feasibility, and meets the high-efficiency query needs in complex data interaction scenarios.
Smart Images

Figure CN121901264A_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the fields of artificial intelligence, natural language processing and databases, and specifically relates to a method for generating SQL for multi-table associations based on graph structure reasoning. Background Technology
[0002] With the development of artificial intelligence and big data, the need for database interaction among business personnel in vertical industries is becoming increasingly urgent. Natural language query aims to transform users' natural language intent into executable SQL to lower the data acquisition threshold and improve decision-making efficiency, serving as a key support for data value mining in vertical industries. However, in real-world scenarios, core data in vertical industries is often stored in relational databases in the form of multi-table joins. How to enable the system to accurately understand cross-table query intent and infer the correct join path based on the underlying database structure has become a key challenge for this technology.
[0003] While current natural language query technology has some applicability in single-table scenarios, it still has significant limitations in generating SQL for multi-table joins in vertical domains: First, the reasoning of join paths lacks structured support. Existing methods mostly rely on text semantic matching to determine join relationships, failing to fully utilize the inherent graph structure features of databases, resulting in a high error rate in path reasoning in complex multi-table scenarios. Second, there is insufficient semantic understanding of vertical domains. Existing models have not effectively incorporated domain knowledge, making it difficult to accurately map natural language professional expressions to data table fields, which easily leads to semantic bias. Third, it is difficult to balance SQL generation efficiency and accuracy. Traditional methods use brute-force search to improve path coverage, which consumes computational resources and easily generates redundant and inefficient SQL, failing to meet users' needs for query response speed and result accuracy.
[0004] This invention proposes a method for generating SQL statements for multi-table associations based on graph structure reasoning. By introducing structured graph modeling and semantic fusion mechanisms, this method constructs a collaborative modeling system for natural language semantics and database structural information. It can accurately parse user query intent in scenarios with complex multi-table associations and stably generate SQL statements with compliant structure and semantic matching. This effectively improves the automation and intelligence level of multi-table knowledge queries and meets the high-efficiency query needs in complex data interaction scenarios. Summary of the Invention
[0005] (a) Technical problems to be solved The technical problem to be solved by this invention is how to provide a method for generating SQL for multi-table associations based on graph structure reasoning, so as to solve the problem that current natural language query technology has certain applicability in single-table scenarios, but still has significant limitations in generating SQL for multi-table associations in vertical domains.
[0006] (II) Technical Solution To address the aforementioned technical problems, this invention proposes a method for generating multi-table join SQL based on graph structure reasoning, which includes the following steps: Step 1: Coding End Double Alignment Modeling Stage First, the database schema information is structured and modeled, constructing a graph structure representation of data tables, fields, and their foreign key relationships. A graph neural network is then used to learn structural embeddings, enabling node features to capture topological dependencies and semantic similarities between fields. Simultaneously, a pre-trained language model is used to semantically encode natural language queries, extracting intent words, entities, operation predicates, and constraint components from the query and encoding them as contextual semantic vectors. A bimodal information interaction mechanism is introduced, allowing text features to form a semantically aware attentional distribution in the structural graph. Structural node features also adaptively adjust their representation weights according to the semantic context, thereby establishing an alignable representation between the semantic space and the structural space. Step Two: Graph Structure Reasoning and Semantic Constraint Path Reasoning Stage By utilizing the aligned embeddings obtained during the encoding phase, a multi-level graph reasoning module is constructed to explicitly model the association paths between multiple tables. The model performs message passing and attention propagation on the graph, and combines the structural adjacency relationship and semantic similarity between nodes to form a multi-hop connection candidate set. Using a semantic constraint reasoning mechanism, the operational intent, domain terminology, and contextual constraints in natural language are transformed into path filtering signals. The candidate paths are weighted and dynamically pruned. At the same time, combined with domain knowledge constraint information, the rationality of the path is verified in a structured manner to ensure that the generated table connection sequence is logically executable and semantically consistent. Step 3: Efficient Generation and Structural Constraints at the Decoding End Based on the path and constraint information obtained through inference, a structure-aware decoder is used to generate the final SQL statement. During the decoding process, the decoder incorporates a syntax tree template and a structural constraint matrix to generate clauses hierarchically. A dynamic programming constraint search strategy is designed to prune generated paths that do not conform to structural constraints or semantic consistency in real time, and an execution feedback mechanism is used to update and optimize the model parameters. Finally, the output SQL is semantically consistent with the query intent. Figure 1 It is consistent with the principle of high feasibility and computational efficiency at the execution level.
[0007] (III) Beneficial Effects This invention proposes a multi-table join SQL generation method based on graph structure reasoning. By first achieving semantic and structural alignment modeling, and then performing graph structure reasoning and hierarchical SQL generation, it effectively solves the problem of inaccurate mapping between natural language and SQL structure in complex multi-table join scenarios, and better utilizes the cross-modal information of database schema and natural language. Simultaneously, by interactively reasoning with graph structure features and semantic features, the model can fully explore the deep connections between table topological relationships and query semantics, extracting structured knowledge from limited multi-table data, and exhibiting good generalization ability in multi-table database query scenarios.
[0008] This invention discloses a cross-modal document information extraction method based on spatial-semantic alignment, the main advantages of which are reflected in the following aspects: (1) A structure-semantic encoding end double alignment mechanism was designed. By jointly modeling the database schema structure and natural language semantic information in the encoding stage, the two-way alignment and fusion of structural features and semantic features are realized, enabling the model to perceive the topological dependency and query intent between fields in a unified semantic space, thereby improving the semantic understanding and pattern matching ability in complex multi-table scenarios.
[0009] (2) A graph structure reasoning and semantic constraint path reasoning module was designed. The explicit and implicit associations between multiple tables were modeled by graph structure reasoning. The semantic constraint mechanism was introduced to screen and verify candidate paths, thereby realizing semantic-driven path reasoning and dynamic optimization, which improved the accuracy, robustness and interpretability of multi-table association paths.
[0010] (3) An efficient SQL generation method based on structural constraints was designed. In the decoding stage, a hierarchical generation method based on syntax tree templates and structural constraint matrices was adopted to generate logically complete and syntactically correct SQL. Combined with a dynamic programming constraint search strategy, generation paths that do not conform to semantic consistency or structural constraints are pruned in real time, which improves the computational efficiency and execution feasibility of generation. Attached Figure Description
[0011] Figure 1 This is a flowchart of the method of the present invention. Detailed Implementation
[0012] To make the objectives, contents, and advantages of the present invention clearer, the specific embodiments of the present invention will be described in further detail below with reference to the accompanying drawings and examples.
[0013] This invention proposes a cross-modal document information extraction method based on spatial-semantic alignment, which mainly addresses three aspects of the problem.
[0014] One issue is the insufficient integration of schema and semantic features. In existing multi-table join SQL generation methods, database schema information and natural language semantic representation are separated, making it difficult for the model to accurately map query intent to database structure, thus affecting the accuracy of the generated results. This invention solves the problem of schema and semantic disconnect by using double-aligned modeling at the encoding end, which embeds schema structure and semantic features into a shared representation space, achieving collaborative modeling of structural information and query semantics.
[0015] Secondly, existing methods often rely on explicit foreign key paths or rule templates in multi-table join reasoning, lacking the ability to model implicit relationships and semantic constraints. This results in weak robustness and interpretability of join path selection. This invention introduces a dynamic path search mechanism based on semantic attention onto the database schema graph through graph structure reasoning and semantic constraint path reasoning modules. This enables unified modeling and constraint verification of explicit and implicit joins, thereby improving the accuracy and stability of multi-table join path reasoning.
[0016] Thirdly, there are issues with the lack of structural constraints and insufficient execution efficiency in SQL generation. Traditional SQL generation lacks syntactic hierarchy and structural constraints, making the generation process prone to logical incompleteness and syntax errors. This invention employs a structure-aware generation mechanism at the decoding end, achieving hierarchical generation and path optimization through syntax tree templates and dynamic constraint search strategies, ensuring the semantic consistency of the generated SQL. At the same time, constraint pruning and syntax template reuse improve the computational efficiency and execution accuracy of the generation.
[0017] To achieve accurate queries of natural language in complex multi-table association scenarios, this invention proposes a multi-table association SQL generation method based on graph structure reasoning. The method consists of three stages: double-aligned modeling at the encoding end, graph structure reasoning and semantic constraint path reasoning, and efficient generation and structural constraints at the decoding end. Together, they constitute a cross-modal semantic reasoning process from natural language to multi-table SQL.
[0018] Step 1: In the dual-alignment modeling stage at the encoding end, the database schema information is first structurally modeled, constructing a graph structure representation of data tables, fields, and their foreign key relationships. A graph neural network is then used to learn structural embeddings, enabling node features to capture topological dependencies and semantic similarities between fields. Simultaneously, a pre-trained language model is used to semantically encode natural language queries, extracting intent words, entities, operation predicates, and constraint components from the query and encoding them as contextual semantic vectors. A dual-modal information interaction mechanism is introduced, allowing text features to form a semantically aware attentional distribution in the structural graph. Structural node features also adaptively adjust their representation weights according to the semantic context, thereby establishing an alignable representation foundation between the semantic and structural spaces.
[0019] Step Two: In the graph structure reasoning and semantic constraint path reasoning stages, a multi-level graph reasoning module is constructed using the aligned embeddings obtained in the encoding stage to explicitly model the association paths between multiple tables. The model performs message passing and attention propagation on the graph, combining the structural adjacency relationships and semantic similarities between nodes to form a multi-hop connection candidate set. Using a semantic constraint reasoning mechanism, operational intentions, domain terms, and contextual constraints in natural language are transformed into path filtering signals. Candidate paths are weighted and dynamically pruned. Simultaneously, domain knowledge constraint information is incorporated to achieve structured verification of path rationality, ensuring that the generated table connection sequences are logically executable and semantically consistent. Through this graph structure reasoning approach, the model can proactively capture implicit associations within the search space, thereby significantly reducing the path reasoning error rate and enhancing the interpretability of multi-table scenarios. Domain knowledge constraints are not presented as an independent module but are integrated into the core reasoning process. In the path reasoning stage, domain terminology matching relies on domain knowledge support, and the judgment of logical executableness during path scoring (such as legal table connection rules within the domain) includes domain knowledge constraints.
[0020] Step 3: In the efficient generation and structural constraint stage at the decoding end, based on the path and constraint information obtained through inference, a structure-aware decoder generates the final SQL statement. During the decoding process, the decoder introduces a syntax tree template and a structural constraint matrix to generate SELECT, JOIN, WHERE, and other clauses in a hierarchical manner, ensuring the logical completeness and syntactic correctness of the generated results. To balance generation speed and accuracy, a dynamic programming constraint search strategy is designed to prune generated paths that do not conform to structural constraints or semantic consistency in real time, and to update and optimize model parameters in conjunction with an execution feedback mechanism. Ultimately, the SQL output by the system is semantically consistent with the query intent. Figure 1 It is consistent with the principle of high feasibility and computational efficiency at the execution level.
[0021] Example 1: Step 1: Double Alignment Modeling at the Encoding End The dual-alignment modeling at the encoding end aims to establish a cross-modal aligned representation of database schema structure and natural language query semantics, providing a unified feature foundation for subsequent inference and realizing bidirectional perception and adaptive adjustment of text semantics and structural information.
[0022] First, the database schema information is structured and modeled, and the database is parsed into a directed graph. , where the node set Including data tables and fields, each Edge set corresponds to a data table or field. Indicates foreign key references or inter-table relationships. For each node... Extract its attribute feature triples, including: field name Field type Table of Attribution And through a graph neural network encoder The structural embedding of the learning nodes is as follows: (1) in, For nodes Structural feature vectors ( (As a feature dimension), this vector aggregates adjacent node information and captures topological dependencies (such as foreign key transitive relationships) and semantic similarities (such as semantic associations between fields in the same table) between fields, enabling structural features to have the ability to perceive the logical association between tables and fields.
[0023] Then, semantic encoding is performed on the natural language query, let the natural language query be... The pre-trained language model RoBERTa is used to encode the contextual semantics of the word, resulting in the semantic embedding of each word. ,as follows: (2) in, For words Contextual semantic vector, semantic feature sequence This includes core semantic information such as intent words, entities, operation predicates, and constraint components in the query.
[0024] To achieve dynamic alignment between structure and semantics, a bidirectional interactive attention mechanism is introduced, calculating the attention weights for "structure → semantics" and "semantics → structure" respectively. A structural feature matrix is defined. (by all) (Constructed by concatenating rows), then the attention weight matrix from structure to semantics is: The calculation process is as follows: (3) in, For learnable parameters, Used to scale attention scores to avoid gradient saturation; Similarly, the attention weight matrix from semantics to structure The calculation process is as follows: (4) Based on the aforementioned attention weights, structural and semantic features are weighted and fused to obtain the aligned embedding for each node. ,as follows: (5) in, and They are respectively and The attention weights of the corresponding nodes in the process. ; Fusion feature set It achieves representation alignment between semantic space and structural space.
[0025] For example: The database has n structure nodes, each node corresponding to a h. i All n h i A natural language query has m words, each word corresponding to a t. j Therefore, there are m t's. j Each structural node incorporates semantic information, meaning that each structural node retains its structural features h. i It also includes the relevant semantics from the query (from m t) j Select what you find useful and integrate it.
[0026] For example: Suppose there are two tables in the database, a student table (containing "student ID, name, class" fields) and a course table (containing "course ID, course name, credit" fields), each with 3 fields. Then the structure nodes n=8, and each node corresponds to h. i The natural language query is "query Zhang San's math score", which can be broken down into the words "query, Zhang San, of, math, score", totaling m=5 words, each corresponding to t. i Now, we need to integrate the semantics of the query into each structural node. For example, "student table" needs to be combined with the semantics of "Zhang San," and "course name" needs to be combined with the semantics of "mathematics." Ultimately, we need to generate a new representation f for each of these 8 structural nodes, incorporating the corresponding semantics. i Therefore, f i There are 8 (consistent with the structure node n, and unrelated to the number of query terms m).
[0027] 2.t i and h i The range of i is inconsistent, h i i is the structure node index (1~n), t i Essentially, it is the weighted fusion result of m semantic word features, where the index i points to the semantic feature vector corresponding to the i-th structural node, not the i-th semantic word. Therefore, t here i You cannot write t directly. j .
[0028] Step Two: Graph Structure Reasoning and Semantic Constraint Path Reasoning Graph structure reasoning and semantic constraint path reasoning stages based on alignment embedding By explicitly modeling multi-table association paths and combining semantic constraints to select reasonable paths, reasoning about multi-table association relationships can be achieved.
[0029] First, perform multi-level graph messaging to model multi-table relationships, let the first... Layer node features Then the first The layer node state is updated by aggregating adjacent node information as follows: (6) in, for Activation function For nodes The set of adjacent nodes, For the first Layer learnable weight matrix, Adjacent nodes right Weighted attention. The initial features of a node are provided by the aligned embedding F, i.e., the first... =0 layer node characteristics It's about alignment and embedding. Then, based on this initial feature, through the formula Perform multi-level message passing to update node status.
[0030] Attention weight Driven by the similarity between query semantics and node features, this ensures that the reasoning process focuses on paths relevant to the query intent. The calculation method is as follows: (7) in, This is for semantic embedding of operational predicates or constraint components in the query. The cosine similarity function (i.e., ...) is used. This mechanism guides path reasoning with semantic constraints and dynamically enhances the node weights related to the query intent.
[0031] After multiple layers of message passing, a set of candidate paths for multi-hop connections is generated. Each path This represents the sequence of associations from the starting table to the target table. To filter out semantically matching and structurally sound paths, a path scoring function is used. The calculation is as follows: (8) in, This is a semantic matching function that calculates the semantic embedding of the query. With path embedding Cosine similarity implementation, This is a structural rationality function used to calculate structural features such as foreign key consistency and join direction validity in the path. Its value range is [0,1]. To balance the weighting of semantics and structure, a scoring function is used to perform weighted evaluation and dynamic pruning of candidate paths, ultimately selecting the path with the highest score. As a sequence of table joins, it is ensured that it is logically executable and semantically consistent with the query intent.
[0032] Path embedding refers to the sequence of associations from the starting table to the target table. p k The vectorized representation of the path integrates the semantic and structural information of nodes and edges, enabling the path to participate in semantic matching calculations as a numerical vector. The path embedding calculation is as follows: ① Node feature initialization: The semantic embedding of each node in the path is used as the initial feature. .
[0033] ② Multi-layer message passing aggregation: Iterative aggregation of features of adjacent nodes in the path, such as the node features of the l-th layer. The sum is calculated by weighting the features of its neighboring nodes.
[0034] ③ Path-level feature aggregation: After multi-layer message passing is completed, the final features of all nodes in the path are integrated to obtain the overall embedding of the path. .
[0035] The calculations primarily revolve around two structural features: foreign key consistency and join direction validity. Foreign key consistency is used to verify the validity of foreign key references between tables in a path. Specifically, for two adjacent tables T1 and T2 in a path, it is necessary to check whether the foreign key column in T1 can find a matching value in the primary key of T2. If all foreign key references are valid, the score for this dimension is close to 1; if there are invalid references (foreign key values do not exist in the referenced table), the score decreases, or even becomes 0.
[0036] The validity of the connection direction is used to ensure that the connection between tables conforms to the business logic. For example, in the connection of table T1→table T2, if there is a reverse connection of T2→T1, the direction is invalid. It can be verified by a predefined connection direction rule base. A valid direction gets 1 point and an invalid direction gets 0 points.
[0037] Finally, the structural features of foreign key consistency and connection direction legality are weighted and calculated, and the scores of each sub-item are integrated into a single value in the range [0,1] to reflect the structural legality of the path.
[0038] Step 3: Efficient Generation and Structural Constraints at the Decoding End The decoding end generates SQL statements that conform to syntax rules and semantic intent based on the table join paths and constraint information obtained through reasoning, and improves the generation efficiency and accuracy through structural constraints and dynamic pruning.
[0039] SQL statements are generated using a structure-aware decoder that aligns with the embedded... Optimal path and query constraint information (The input should include filtering conditions, aggregation operations, and query constraint information C, which are constraints at the semantic and business logic levels.) The output should be a complete sentence as follows: (9) The decoder uses a Transformer architecture, and its attention mechanism is subject to a structural constraint matrix. Regulation (the structural constraint matrix M controls the legal connections between nodes, such as foreign key associations, to ensure that the generated JSON clauses conform to the structural constraints of the database model; this is a constraint at the database structure level, different from the query constraint information C), where... Represents a node and Valid joins are allowed (e.g., foreign key relationships exist); otherwise... Ensure that the generated JOIN clause conforms to the database schema constraints.
[0040] Meanwhile, the syntax tree template introduced by the decoder is not simply sorted, but rather uses hierarchical logical dependencies as its framework: first, it generates a FROM clause based on the main table of graph reasoning to anchor the data source; then, it generates a JOIN clause based on the multi-table join path to clarify the join tables and foreign key conditions to ensure legality; subsequently, it generates a SELECT clause based on semantically aligned field matching, limiting the selected fields to the declared tables to avoid undefined field errors; finally, it generates a WHERE clause based on natural language constraints, whose fields come from the declared tables and whose operators match the field types. This progressive logic of "data source → join extension → operation object → filtering conditions" creates a closed loop of mutual constraints between clauses, ensuring the logical completeness of SQL in terms of table joins, fields, and conditions.
[0041] To balance generation speed and accuracy, a dynamic programming constraint search strategy is designed to prune generated branches that do not meet structural constraints or semantic consistency in real time. The pruning function Prune is defined, and its calculation process is as follows: (10) in, For the generation branch in the decoding process, if If the branch is not found to be valid, it is pruned to reduce invalid searches. Simultaneously, an execution feedback mechanism is introduced, converting the execution results of the generated SQL in the database (such as whether errors occur, and the degree of match between the returned results and the query intent) into a loss signal, which is then used to update the model parameters via gradient descent. ,as follows: (11) in, For model parameters, For learning rate, To create a joint loss function that combines semantic loss and execution loss, The gradient operator represents the gradient with respect to the loss function. Regarding model parameters Taking the partial derivative yields the direction and magnitude information of the parameter update. Natural Language Query refers to the text instructions entered by the user to generate SQL. ExecRes refers to the SQL execution results, which are the outputs of the generated SQL after it is actually executed in the database (such as whether there are errors, whether the returned data matches the query intent, etc.).
[0042] The joint loss function integrates semantic loss and execution loss in a linearly weighted manner.
[0043] Semantic loss uses cross-entropy loss to measure the semantic matching degree between the generated SQL and the natural language query Q. Treating SQL generation as a sequence generation task, cross-entropy can be used to measure the difference between the predicted SQL token and the real SQL.
[0044] Suppose a user query Q represents all users older than 30. The target SQL is `SELECT name FROM users WHERE age>30`, while the predicted SQL is `SELECT age FROM users WHERE age<30`. Cross-entropy loss measures the difference between the predicted probability distribution and the true distribution. Assume that predicting each token (e.g., SELECT, name, FROM, etc.) in the SQL generation task is a classification problem, with the true token label being 1 and others being 0. The sum of the model's predicted probability for each token and the cross-entropy of the true label is the semantic loss. For example, for the token "SELECT", the true label is 1. If the model predicts its probability as 0.6, and the sum of the predicted probabilities of other tokens (e.g., UPDATE, DELETE, etc.) is 0.4, then the cross-entropy of this token is... log(0.6). By summing the cross-entropy of all tokens, we obtain the semantic loss generated by the SQL.
[0045] The execution loss uses a 0-1 loss to quantify the effectiveness of the generated SQL in the database. A loss of 1 is returned if the generated SQL does not match the query intent, and 0 if it is valid. For example, if the generated SQL is `SELECT name FROM users WHERE age>30;` and returns the names of users who meet the criteria, perfectly matching the query intent, the execution loss is 0. Conversely, if the generated SQL is `SELECT name FROM users WHERE age<30;` and returns the names of users under 30, conflicting with the query intent, the execution loss is 1.
[0046] Beneficial effects: This invention presents a multi-table join SQL generation method based on graph structure reasoning. By first achieving semantic and structural alignment modeling, and then performing graph structure reasoning and hierarchical SQL generation, it effectively solves the problem of inaccurate mapping between natural language and SQL structure in complex multi-table join scenarios, and better utilizes cross-modal information between database schema and natural language. Simultaneously, by interactively reasoning with graph structure features and semantic features, the model can fully explore the deep connections between table topological relationships and query semantics, extracting structured knowledge from limited multi-table data, and exhibiting good generalization ability in multi-table database query scenarios.
[0047] This invention discloses a cross-modal document information extraction method based on spatial-semantic alignment, the main advantages of which are reflected in the following aspects: (1) A structure-semantic encoding end double alignment mechanism was designed. By jointly modeling the database schema structure and natural language semantic information in the encoding stage, the two-way alignment and fusion of structural features and semantic features are realized, enabling the model to perceive the topological dependency and query intent between fields in a unified semantic space, thereby improving the semantic understanding and pattern matching ability in complex multi-table scenarios.
[0048] (2) A graph structure reasoning and semantic constraint path reasoning module was designed. The explicit and implicit associations between multiple tables were modeled by graph structure reasoning. The semantic constraint mechanism was introduced to screen and verify candidate paths, thereby realizing semantic-driven path reasoning and dynamic optimization, which improved the accuracy, robustness and interpretability of multi-table association paths.
[0049] (3) An efficient SQL generation method based on structural constraints was designed. In the decoding stage, a hierarchical generation method based on syntax tree templates and structural constraint matrices was adopted to generate logically complete and syntactically correct SQL. Combined with a dynamic programming constraint search strategy, generation paths that do not conform to semantic consistency or structural constraints are pruned in real time, which improves the computational efficiency and execution feasibility of generation.
[0050] The above description is only a preferred embodiment of the present invention. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the technical principles of the present invention, and these improvements and modifications should also be considered within the scope of protection of the present invention.
Claims
1. A method for generating SQL for multi-table joins based on graph structure reasoning, characterized in that, The method includes the following steps: Step 1: Coding End Double Alignment Modeling Stage First, the database schema information is structured and modeled, constructing a graph structure representation of data tables, fields, and their foreign key relationships. A graph neural network is then used to learn structural embeddings, enabling node features to capture topological dependencies and semantic similarities between fields. Simultaneously, a pre-trained language model is used to semantically encode natural language queries, extracting intent words, entities, operation predicates, and constraint components from the query and encoding them as contextual semantic vectors. A bimodal information interaction mechanism is introduced, allowing text features to form a semantically aware attentional distribution in the structural graph. Structural node features also adaptively adjust their representation weights according to the semantic context, thereby establishing an alignable representation between the semantic space and the structural space. Step Two: Graph Structure Reasoning and Semantic Constraint Path Reasoning Stage By utilizing the aligned embeddings obtained during the encoding phase, a multi-level graph reasoning module is constructed to explicitly model the association paths between multiple tables. The model performs message passing and attention propagation on the graph, and combines the structural adjacency relationship and semantic similarity between nodes to form a multi-hop connection candidate set. Using a semantic constraint reasoning mechanism, the operational intent, domain terminology, and contextual constraints in natural language are transformed into path filtering signals. The candidate paths are weighted and dynamically pruned. At the same time, combined with domain knowledge constraint information, the rationality of the path is verified in a structured manner to ensure that the generated table connection sequence is logically executable and semantically consistent. Step 3: Efficient Generation and Structural Constraints at the Decoding End Based on the path and constraint information obtained through reasoning, a structure-aware decoder is used to generate the final SQL statement. During the decoding process, the decoder introduces a syntax tree template and a structural constraint matrix to generate clauses in a hierarchical manner. A dynamic programming constraint search strategy is designed to prune generated paths that do not meet structural constraints or semantic consistency in real time, and to update and optimize model parameters in conjunction with an execution feedback mechanism. Finally, the output SQL is consistent with the query intent at the semantic level, and has high feasibility and computational efficiency at the execution level.
2. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 1, characterized in that, Step one, which involves structured modeling of the database schema information, includes: Structured modeling of database schema information is performed, and the database is parsed into a directed graph. , where the node set Including data tables and fields, each Edge set corresponds to a data table or field. Indicates foreign key references or inter-table relationships; for each node Extract its attribute feature triples, including: field name Field type Table of Attribution And through a graph neural network encoder The structural embedding of the learning nodes is as follows: (1) in, For nodes The structural feature vector, As a feature dimension, this vector aggregates adjacent node information and captures topological dependencies and semantic similarities between fields, enabling structural features to have the ability to perceive the association logic between tables and fields.
3. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 2, characterized in that, In step one, semantic encoding of the natural language query using a pre-trained language model includes: Semantic encoding is performed on natural language queries. Let the natural language query be... The pre-trained language model RoBERTa is used to encode the contextual semantics of the word, resulting in the semantic embedding of each word. ,as follows: (2) in, For words Contextual semantic vector, semantic feature sequence This includes semantic information about intent words, entities, operation predicates, and constraint components in the query.
4. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 1, characterized in that, In step one, a bimodal information interaction mechanism is introduced, enabling text features to form a semantically aware attention distribution in the structure graph. The structural node features also adaptively adjust their representation weights according to the semantic context, thereby establishing an alignable representation between the semantic space and the structure space, including: To achieve dynamic alignment between structure and semantics, a bidirectional interactive attention mechanism is introduced, calculating the attention weights for "structure → semantics" and "semantics → structure" respectively; a structural feature matrix is defined. , by all Concatenated line by line, the attention weight matrix from structure to semantics is: The calculation process is as follows: (3) in, For learnable parameters, Used to scale attention scores to avoid gradient saturation; Similarly, the attention weight matrix from semantics to structure The calculation process is as follows: (4) Based on the aforementioned attention weights, structural and semantic features are weighted and fused to obtain the aligned embedding for each node. ,as follows: (5) in, and They are respectively and The attention weights of the corresponding nodes in the process. ; Fusion feature set It achieves representation alignment between semantic space and structural space.
5. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 4, characterized in that, In step two, the alignment embeddings obtained during the encoding phase are used to construct a multi-level graph reasoning module to explicitly model the association paths between multiple tables, including: First, perform multi-level graph messaging to model multi-table relationships, let the first... Layer node features Then the first The layer node state is updated by aggregating adjacent node information as follows: (6) in, for Activation function For nodes The set of adjacent nodes, For the first Layer learnable weight matrix, Adjacent nodes right Weighted attention; the initial features of a node are provided by the aligned embedding F, i.e., the first... l =0 layer node characteristics It's about alignment and embedding. Then, based on this initial feature, through the formula Perform multi-level message passing to update node status; Attention weight Driven by the similarity between query semantics and node features, this ensures that the reasoning process focuses on paths relevant to the query intent. The calculation method is as follows: (7) in, This is for semantic embedding of operational predicates or constraint components in the query. The cosine similarity function is used, which enables path reasoning to be guided by semantic constraints and dynamically enhances the node weights related to the query intent.
6. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 5, characterized in that, In step two, the model performs message passing and attention propagation on the graph, integrates the structural adjacency relationships and semantic similarities between nodes to form a multi-hop connection candidate set, and uses a semantic constraint reasoning mechanism to transform operational intentions, domain terms, and contextual constraints in natural language into path selection signals. Candidate paths are then weighted and dynamically pruned. Simultaneously, domain knowledge constraint information is incorporated to achieve structured verification of path rationality, including: After multiple layers of message passing, a set of candidate paths for multi-hop connections is generated. Each path This represents the sequence of associations from the starting table to the target table; to filter out semantically matching and structurally reasonable paths, a path scoring function is used. The calculation is as follows: (8) in, This is a semantic matching function that calculates the semantic embedding of the query. With path embedding Cosine similarity implementation, This is a structural rationality function used to calculate the structural features of foreign key consistency and join direction legality in the path. Its value range is [0,1]. To balance the weighting of semantics and structure, this scoring function is used to perform weighted evaluation and dynamic pruning of candidate paths, ultimately selecting the path with the highest score. As a table join sequence, it is ensured that it is logically executable and semantically consistent with the query intent.
7. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 6, characterized in that, Path embedding refers to the sequence of associations from the starting table to the target table. p k The vectorized representation of the path integrates the semantic and structural information of nodes and edges, enabling the path to participate in semantic matching calculations as a numerical vector; the path embedding calculation is as follows: ① Node feature initialization: The semantic embedding of each node in the path is used as the initial feature. ; ② Multi-level message passing aggregation: Iterative aggregation of features of adjacent nodes in the path, the first... l Layer node features The summation is weighted by the characteristics of its neighboring nodes; ③ Path-level feature aggregation: After multi-layer message passing is completed, the final features of all nodes in the path are integrated to obtain the overall embedding of the path. .
8. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 6, characterized in that, The calculation revolves around two structural features: foreign key consistency and join direction validity. Foreign key consistency is used to verify whether the foreign key references between tables in the path are valid. For two adjacent tables T1 and T2 in the path, it is necessary to check whether the foreign key column in T1 can find a matching value in the primary key of T2. If all foreign key references are valid, the score of this dimension is close to 1. If there are invalid references, the score will decrease or even become 0. The validity of the connection direction is used to ensure that the connection between tables conforms to the business logic. In the connection of table T1→table T2, if there is a reverse connection of T2→T1, the direction is invalid. It is validated by a predefined connection direction rule base. A valid direction gets 1 point and an invalid direction gets 0 points. Finally, the structural features of foreign key consistency and connection direction legality are weighted and calculated, and the scores of each sub-item are integrated into a single value in the range [0,1] to reflect the structural legality of the path.
9. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 6, characterized in that, In step three, based on the path and constraint information obtained through reasoning, a structure-aware decoder is used to generate the final SQL statement. During the decoding process, the decoder incorporates a syntax tree template and a structural constraint matrix to generate clauses in a hierarchical manner, including: SQL statements are generated using a structure-aware decoder that aligns with the embedded... Optimal path and query constraint information Given the input, the complete output sentence is as follows: (9) The decoder uses a Transformer architecture, and its attention mechanism is subject to a structural constraint matrix. Regulation, among which Represents a node and A valid connection is allowed; otherwise... Ensure that the generated JOIN clause conforms to the database schema constraints; Meanwhile, the decoder introduces a syntax tree template, using hierarchical logical dependencies as its framework: first, it generates a FROM clause based on the main table of graph reasoning to anchor the data source; then, it generates a JOIN clause based on the multi-table join path to clarify the join tables and foreign key conditions to ensure legality; subsequently, it generates a SELECT clause based on semantically aligned field matching, limiting the selected fields to the declared tables to avoid undefined field errors; finally, it generates a WHERE clause based on natural language constraints, with its fields coming from the declared tables and the operators matching the field types; this progressive logic of "data source → join extension → operation object → filter condition" creates a closed loop of mutual constraints between clauses, ensuring the logical completeness of SQL in terms of table joins, fields, and conditions.
10. The method for generating multi-table join SQL based on graph structure reasoning as described in claim 9, characterized in that, In step three, a dynamic programming constraint search strategy is designed to prune generated paths that do not meet structural constraints or semantic consistency in real time, and to update and optimize model parameters in conjunction with an execution feedback mechanism. Ultimately, the output SQL is semantically consistent with the query intent, and at the execution level, it possesses high feasibility and computational efficiency, including: To balance generation speed and accuracy, a dynamic programming constraint search strategy is designed to prune generated branches that do not meet structural constraints or semantic consistency in real time. The pruning function Prune is defined, and its calculation process is as follows: (10) in, For the generation branch in the decoding process, if If the branch fails to perform a valid search, it is pruned to reduce invalid searches. Simultaneously, an execution feedback mechanism is introduced, converting the execution results of the generated SQL in the database into a loss signal, which is then used to update the model parameters via gradient descent. ,as follows: (11) in, For model parameters, For learning rate, To create a joint loss function that combines semantic loss and execution loss, The gradient operator represents the gradient with respect to the loss function. Regarding model parameters Taking the partial derivative yields the direction and magnitude information of the parameter update. It is a natural language query, which is a text command input by the user to generate SQL. ExecRes is the SQL execution result, which refers to the output of the generated SQL after it is actually executed in the database. The joint loss function integrates semantic loss and execution loss in a linearly weighted manner. Semantic loss uses cross-entropy loss to measure the semantic matching degree between the generated SQL and the natural language query Q. SQL generation is regarded as a sequence generation task, and cross-entropy is used to measure the difference between the predicted SQL token and the real SQL. Execution loss uses 0-1 loss to quantify the effectiveness of the generated SQL in the database. If the result returned after the generated SQL is executed does not match the query intent, it returns 1; otherwise, it returns 0.