Method and system for generating SQL (Structured Query Language) query based on natural language problem

By employing cross-encoder filtering and large language model correction methods, the problems of table schema joining and context fusion in NL2SQL are solved, achieving highly accurate and robust SQL generation that meets practical application needs.

CN121387943APending Publication Date: 2026-01-23STATE GRID JIANGSU ELECTRIC POWER CO LIANYUNGANG POWER SUPPLY CO +1
View PDF 0 Cites 3 Cited by

Patent Information

Application Number
CN202511385459.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-09-26
Publication Date
2026-01-23

AI Technical Summary

Technical Problem

Existing natural language to SQL (NL2SQL) methods lack accuracy and robustness in table schema information linking, context fusion, and SQL generation, making it difficult to automatically correct subtle errors, resulting in generated queries that cannot be executed directly or produce incorrect results.

Method used

A cross-encoder structure based on attention mechanism is adopted to filter database patterns. Through decoupled generation strategy and dynamic correction of large language model, the transformation of natural language questions into SQL queries is realized.

Benefits of technology

It improves the accuracy of matching natural language problems with database schemas, reduces the complexity of SQL generation, significantly reduces subtle errors, and enhances the executability and robustness of queries.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121387943A_ABST
    Figure CN121387943A_ABST
Patent Text Reader

Abstract

The invention discloses a method and a system for generating an SQL (Structured Query Language) query based on a natural language question. The method comprises the following steps: converting mode information of a target database and the natural language question into semantic vector representation; based on the semantic vector representation, a simplified database mode set related to SQL query is screened out through an attention mechanism; based on the natural language problem, the simplified database mode set and preset database constraint information, generating an SQL structural skeleton, and filling specific elements of the SQL structural skeleton to form a preliminary SQL query; and performing dynamic correction and verification on the initial SQL query by utilizing a large language model, and outputting a final SQL query. According to the method, association mining between user query and a database mode is effectively enhanced by utilizing a context-aware cross-encoder mechanism, and an implicit corresponding relation between a natural language problem and a database table / column can be more accurately identified and utilized.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The present application belongs to the field of natural language processing, and particularly relates to a method and system for generating SQL queries based on natural language questions. BACKGROUND

[0002] NL2SQL technology aims to realize the automatic conversion of natural language to database query statements, allowing users to directly obtain information in the database through daily language. However, existing NL2SQL methods still have many difficulties and deficiencies in practical applications. One major challenge is the table schema information linking problem: the words in the natural language question and the tables and columns in the target database schema often have name mismatches or semantic implications, making it difficult for the model to accurately find the corresponding tables and columns. Secondly, the context fusion of natural language questions and database schema information is insufficient, making it difficult for the model to understand both user intent and database structure, and missing key associations in complex queries involving multiple tables. In addition, traditional methods have high coupling when parsing SQL structure and selecting database information, i.e., often deciding the logical structure of SQL and the involved table columns in the same stage. This integrated strategy is prone to errors and difficult to debug. Finally, the generated SQL queries often have some minor errors, such as missing necessary JOIN conditions, mismatched parentheses or aliases, etc. These errors are usually difficult for the system to automatically detect and correct, resulting in queries that cannot be directly executed or incorrect results.

[0003] In summary, how to improve the matching accuracy between natural language questions and database information, reduce the complexity of the SQL generation process, and automatically correct minor errors in the generated results is a core problem that needs to be solved in current NL2SQL technology. Some existing researches have begun to try to solve part of the above problems. For example, the DIN-SQL method proposed in recent years uses a structured representation and instruction fine-tuning strategy to filter the most relevant database tables and columns through schema linking, and combines a multi-stage generation mechanism to first determine the query structure and then generate specific SQL content. However, even with these improvements, existing methods have not been able to solve the problem of automatically correcting minor errors in the generated results, and the executability and robustness of the generated SQL still have room for improvement. SUMMARY

[0004] To solve the problems existing in the prior art, the present application proposes a method and system for generating SQL queries based on natural language questions.

[0005] The technical solution of the present application is as follows: A method for generating SQL queries based on natural language questions, the SQL queries acting on a target database to obtain query results for corresponding natural language questions, the method comprising: transforming the schema information of the target database and the natural language question into semantic vector representations; based on the semantic vector representations, filtering out a set of simplified database schemas related to the SQL query through an attention mechanism; based on the natural language question, the set of simplified database schemas, and preset database constraint information, generating an SQL skeleton and filling in specific elements of the SQL skeleton to form a preliminary SQL query; using a large language model to dynamically correct and verify the preliminary SQL query, and outputting a final SQL query.

[0006] Further, the specific method of transforming the schema information of the target database and the natural language question into semantic vector representations includes: concatenate the complete schema information of the target database composed of all table names and their respective column names with the natural language question in sequence to form a text input sequence composed of several words and input it to a pre-trained language model for encoding to obtain the context representation of each word in the text input sequence. Then, perform a pooling operation on the context representation to extract a global semantic vector corresponding to the natural language question and initial representation vectors of each table and column in the target database.

[0007] Further, the specific method of filtering out a set of simplified database schemas related to the SQL query through an attention mechanism based on the semantic vector representations includes: adopting a cross-encoder structure based on a context-aware attention mechanism to enhance the context of tables and columns, performing attention interaction between the global semantic vector and the initial representation vectors of each table and column to obtain enhanced table representations and enhanced column representations that have fused question context information; performing table-column multi-head attention fusion processing on the enhanced table representations and their column enhanced representations to obtain context fusion representations; performing table relevance processing on the enhanced table representations and the context fusion representations to obtain table relevance scores; performing sorting and filtering processing based on the table relevance scores to obtain Top-K1 candidate tables; performing table relevance processing on the enhanced column representations and the context fusion representations corresponding to each column in the Top-K1 candidate tables to obtain column relevance scores; performing sorting and filtering processing based on the column relevance scores to obtain Top-K2 candidate columns for each table, which constitute a set of simplified database schemas.

[0008] Further, the specific method of generating an SQL skeleton based on the natural language question, the set of simplified database schemas, and preset database constraint information, and filling in specific elements of the SQL skeleton to form a preliminary SQL query includes: The natural language question, the reduced database schema set and the preset database constraint information are sequentially processed and input into a generation model, a skeleton priority strategy is used to generate an SQL structure skeleton, specific element filling processing including table name, column name and constant value is performed on the SQL skeleton structure to obtain a preliminary SQL query.

[0009] Further, the SQL structure skeleton includes SQL keywords and placeholders.

[0010] Further, the generation model is a Seq2Seq model.

[0011] Further, the specific method for outputting the final SQL query by using a large language model to dynamically correct and verify the preliminary SQL query includes: The expected error risk of the preliminary SQL is evaluated to obtain a prompt mode selection result; when there is a significant error, a defect-oriented prompt template is constructed for the preliminary SQL to obtain a large language model input prompt; when only a detail optimization is needed, a gentle review prompt template is constructed for the preliminary SQL to obtain a large language model input prompt; the large language model input prompt is subjected to large language model reasoning processing to obtain a corrected SQL query; the corrected SQL query is subjected to database execution verification processing, and if the verification fails, a rollback mechanism is triggered to output the final SQL query.

[0012] A system for generating an SQL query based on a natural language question, the SQL query being used for a target database to obtain a query result corresponding to the natural language question, the system including a semantic understanding and representation module, a context-aware screening module, a decoupled SQL generation module and an intelligent correction guarantee module. The semantic understanding and representation module is configured to convert schema information of the target database and the natural language question into semantic vector representation. The context-aware screening module is configured to screen a reduced database schema set related to the SQL query based on the semantic vector representation through an attention mechanism. The decoupled SQL generation module is configured to generate an SQL structure skeleton based on the natural language question, the reduced database schema set and preset database constraint information, and fill specific elements of the SQL structure skeleton to form a preliminary SQL query. The intelligent correction guarantee module is configured to use a large language model to dynamically correct and verify the preliminary SQL query and output a final SQL query.

[0013] An electronic device includes a memory and a processor, the memory storing a computer program, and the processor is configured to invoke and run the computer program stored in the memory to execute the method according to any one of the above.

[0014] A computer readable storage medium storing a computer program, the computer program, when executed by a processor, implements the steps of the method of any one of the above. Compared with the prior art, the present application has the following beneficial effects:

[0015] The present application proposes a method and system for generating SQL queries based on natural language questions, which effectively enhances the association mining between user queries and database patterns by using a context-aware cross-encoder mechanism, can more accurately identify and utilize the implicit correspondence between natural language questions and database tables / columns, and greatly improves the accuracy and recall rate of related table column identification.

[0016] The method of the present application reduces the difficulty of direct generation of complex SQL by introducing a two-stage decoupling generation strategy of pattern screening and skeleton prior, makes the overall structure of the generated SQL more rigorous, the syntax more in line with reality, significantly reduces logical errors, and thus improves the executability of the query.

[0017] The method of the present application greatly reduces the subtle errors in the generated SQL and the resulting execution failure conditions by means of intelligent review and directional correction of the preliminary results by a large language model, ensuring the correctness and robustness of the final output query.

[0018] The present application improves the matching accuracy between natural language queries and database patterns (enhances the precision and recall rate of table column identification), reduces the difficulty of complex SQL query generation (reduces the complexity of one-step generation of complete SQL through task decoupling and skeleton guidance), and enhances the automatic error correction capability of the generated SQL results (automatically reviews and corrects subtle errors by using an intelligent model), thereby comprehensively improving the accuracy, executability and robustness of the finally generated SQL query. Therefore, the method of the present application can more efficiently and accurately convert natural language questions into high-quality SQL queries to meet the actual application requirements. BRIEF DESCRIPTION OF DRAWINGS

[0019] Figure 1 A flowchart of the method for generating SQL queries based on natural language questions; Figure 2 A flowchart of the method for automatically reviewing and correcting SQL by using a large language model. DETAILED DESCRIPTION

[0020] The present application will be further illustrated below in conjunction with the drawings and specific embodiments, and it should be understood that these embodiments are only used to illustrate the present application and do not limit the scope of the present application. After reading the present application, those skilled in the art can make various modifications to the present application, and all such modifications fall within the scope defined by the appended claims. Embodiment one:

[0021] A method for generating an SQL query based on a natural language question according to the present application, the SQL query is used to operate on a target database to obtain the query result corresponding to the natural language question, as shown in the following formula (I): Figure 1 The method comprises the following steps: S1, semantic understanding and representation: converting the schema information of the target database and the natural language question into semantic vector representation; S2, context-aware filtering: based on the semantic vector representation, filtering out a set of simplified database schema related to the SQL query through an attention mechanism; S3, decoupled SQL generation: generating an SQL skeleton based on the natural language question, the set of simplified database schema, and the preset database constraint information, and filling in the specific elements of the SQL skeleton to form a preliminary SQL query; S4, intelligent correction guarantee: using a large language model to dynamically correct and verify the preliminary SQL query, and outputting a final SQL query.

[0022] In one embodiment, the conversion of the schema information of the target database and the natural language question into semantic vector representation mainly relies on natural language understanding. The specific method of this step comprises the following steps: The complete schema information of the target database composed of the table names of all tables and the column names of the columns contained in each table is sequentially concatenated with the natural language question to form a text input sequence composed of several words, which is then input into a pre-trained language model (such as RoBERTa) for encoding to obtain the context representation of each word (Token) in the text input sequence. Then, the context representation is pooled to extract the global semantic vector corresponding to the natural language question and the initial representation vector of each table and column in the target database.

[0023] In the specific implementation process, first, input acquisition and encoding are performed to obtain the natural language question input by the user and the complete schema information of the target database, including all table names and their respective column names, etc. Then, the complete schema information of the database is represented in a sequence, for example, the table name of each table and the column name contained therein are connected into a description string, and all the descriptions of the tables are sequentially concatenated to form a complete vector input sequence. Then, a pre-trained language model is used to vectorize the input sequence to obtain the context representation vector of each word in the sequence. On this basis, the global vector representing the entire question semantics is extracted as the question context vector in the subsequent steps.

[0024] Typically, this global semantic representation can be obtained by utilizing special start token representations (e.g., the `[CLS]` vector) or by pooling the token representations of the question part. In this way, the user query (question) and the database structure are fused into the same encoding context, providing a basis for subsequent association analysis.

[0025] In one embodiment, based on the semantic vector representation, the attention mechanism is used to filter out the relevant database schema set of the SQL query, which mainly depends on the context semantic association analysis and the related list filtering. The specific method of this step includes: The cross-encoder structure based on context-aware attention mechanism is used to enhance the context of the table and column. The global semantic vector and the initial representation vector of each table and column are respectively subjected to attention interaction to obtain the enhanced table representation and the enhanced column representation of each table and column that fuse the question context information. The enhanced table representation and the enhanced column representation of each column are subjected to table-column multi-head attention fusion processing to obtain the context fusion representation. The enhanced table representation and the context fusion representation are subjected to table relevance prediction processing to obtain the table relevance score. The table relevance score is subjected to sorting and filtering processing to obtain the Top-K1 candidate tables. The enhanced column representation and the context fusion representation of each column in the Top-K1 candidate tables are subjected to column relevance prediction processing to obtain the column relevance score. The column relevance score is subjected to sorting and filtering processing to obtain the Top-K2 candidate columns of each table, which constitute the simplified database schema set as the input basis for subsequent SQL generation.

[0026] In the specific implementation process, based on the context representation obtained by the above steps, the relevance of each table and column in the database schema is evaluated. In the present application, a cross-encoder with context-aware attention mechanism is used to realize fine relevance extraction.

[0027] Specifically, the global semantic representation vector of the question is first subjected to interactive attention calculation with the initial representation of each table (i.e., question-table attention mechanism) to obtain the enhanced table representation that fuses the question context information. Similarly, the same question semantic vector is subjected to attention calculation with the initial representation of each column to obtain the enhanced column representation that fuses the question semantic. The enhanced table representation refers to the representation of the table after interacting with the query context, and the enhanced column representation refers to the representation of the column after interacting with the query context.

[0028] Through the above "question, table, and question, column attention" processing, each table and column "perceives" the context of the complete question, thereby avoiding the deviation that may be caused by matching only based on part of the words.

[0029] Next, in the table-column cross-attention fusion step, the enhanced table representation of each table is taken as a query vector, the enhanced list corresponding to the table of the table is taken as a key and a value, a multi-head attention mechanism is input to further interact and fuse to generate a context fusion representation. At this time, the context fusion representation not only contains the semantics of the table itself, but also combines the context information of the question and the column to which it belongs, forming a hierarchical semantic fusion.

[0030] Subsequently, the enhanced table representation and the context fusion representation are jointly input into a table relevance predictor to predict the relevance score of each table with the current question. Similarly, the enhanced list representation and the context fusion representation can be jointly input into a column relevance predictor to predict the relevance score of the column.

[0031] According to the predicted relevance score, the schema elements in the database are screened: Preferably, the tables are first sorted in descending order of the score, and the top k1 tables are selected as candidate relevant tables; for each selected table, the columns belonging to the table are sorted according to the relevance, and the top k2 columns in the table are selected as candidate relevant columns.

[0032] After the above screening, a simplified database schema set (including several candidate tables and related columns) highly relevant to the current query can be obtained, and the remaining irrelevant tables and columns are temporarily ignored.

[0033] By introducing the context-aware cross-encoder and sorting and screening mechanism, the present application can more accurately capture the implicit association between natural language questions and database schema items, greatly improving the accuracy and recall rate of relevant schema item extraction; at the same time, it effectively reduces the information range required for subsequent SQL generation, reducing the difficulty of generation and search space.

[0034] In one embodiment, the method for generating an SQL structure skeleton based on a natural language question, a simplified database schema set, and preset database constraint information (such as primary key and foreign key information), and filling specific elements of the SQL structure skeleton to form a preliminary SQL query includes: The natural language question, the simplified database schema set, and the preset database constraint information are sequentially arranged to construct an input sequence of a generation model, the input sequence is input into the generation model, an SQL structure skeleton is generated using a skeleton-first strategy, and specific elements including table names, column names, and constant values are filled into the SQL skeleton structure according to the skeleton content to obtain a preliminary SQL query.

[0035] In one embodiment, the SQL structure skeleton includes SQL keywords and placeholders.

[0036] In one embodiment, the generation model is a Seq2Seq model.

[0037] In the implementation process, the natural language question of the user and the relevant table information (simplified mode set) screened by the above steps and the optional database constraint information (for example, the primary key / foreign key relationship between the related tables) are arranged together to construct an input sequence as a generated model. Preferably, a pre-trained Seq2Seq model is used as the SQL generation model.

[0038] Firstly, the encoder of the model encodes the above input sequence to generate a hidden representation containing the query semantics and the related mode context; Then the SQL query statement is generated by the decoder in an autoregressive manner. In order to ensure the accuracy and rationality of the generated SQL, the application introduces a skeleton-priority decoding strategy: that is, the decoding process of the model is divided into two steps, the framework structure (skeleton) of the SQL is generated first, and then the complete SQL query is generated. The so-called SQL skeleton can be understood as a rough query framework containing only SQL keywords and sentence structure, wherein the details such as table name, column name, constant value and the like are represented by placeholders. For example, for the query "query the names of students in the student table whose age is greater than 18 years old", the SQL skeleton can be expressed as "SELECT column FROM table WHERE column>value". The model outputs a skeleton structure similar to this in the first step; then in the second step, the actual table name "student", column name "name" and "age", and constant "18" are filled in the skeleton to generate the complete SQL query. In order to realize this two-stage generation, the model is designed to have "skeleton sentence + complete SQL sentence" splicing as the target output during training, and the model learns to output the skeleton first and then the complete SQL through special markers or separators. During inference, the model follows the same strategy, first outputs the skeleton and then fills in the details. The skeleton-aware decoding strategy effectively reduces the difficulty of directly generating a complete SQL, makes the model determine the overall structure first and then fill in the specific content, reduces the probability of errors caused by simultaneous generation of structure and details, especially when there are nested queries or complex filtering conditions, this strategy can ensure the correctness of the overall framework, thereby improving the accuracy of the final SQL. After the model generates the preliminary SQL text sequence, the system can perform simple post-processing on it, such as converting possible normalization markers to standard SQL syntax, unifying keyword case, completing missing quotation marks or semicolons, etc., so that the SQL statement meets the requirements of database execution. Then, preferably, the SQL query is tried to be executed on the target database to verify its executability. If the generation model adopts a multi-candidate generation mechanism (such as obtaining multiple SQL candidates through beam search), the application can try to execute the candidate sentences one by one at this stage, and select the first successful execution and the correct and reasonable SQL as the output, thereby improving the reliability of the generated result. Through the above process, the preliminary SQL query generated by the model is obtained.

[0039] In one embodiment, the specific method for dynamically correcting and verifying the preliminary SQL query using a large language model includes: evaluating the risk of expected errors of the preliminary SQL to obtain a prompt mode selection result; when there are significant errors, conducting defect-oriented prompt template construction processing on the preliminary SQL to obtain a large language model input prompt; when only details need to be optimized, conducting mild review prompt template construction processing on the preliminary SQL to obtain a large language model input prompt; conducting large language model inference processing on the large language model input prompt to obtain a corrected SQL query; and conducting database execution verification processing on the corrected SQL query, and if the verification fails, triggering a rollback mechanism to output the final SQL query.

[0040] In specific implementation, for the above preliminary SQL query, the application further adds a stage of automatically reviewing and correcting SQL using a large language model (also referred to as "LLM"). As shown in Figure 2 the prompt information (Prompt) for self-correction task is first constructed, which includes: the original natural language question, the relevant table and column names (the set of simplified modes) and the necessary database details (such as the column name list of each relevant table, the primary-foreign key association relationship between relevant tables, etc.) selected in the above steps, and the preliminary generated SQL query text. If necessary, entity names or specific numerical value condition information appearing in the user question can also be added to help the LLM more accurately check whether the condition settings in the SQL query are reasonable. The well-designed prompt information enables the LLM to not only obtain the SQL that needs to be corrected, but also master the key context information related to the SQL, thereby conducting targeted analysis.

[0041] According to the complexity or quality of the preliminary SQL, the application preferably generates prompt information in two modes: (1) Defect-oriented mode: when the preliminary SQL is expected to have many or large potential errors, the prompt explicitly requires the LLM to check and "fix any possible errors". For example, the prompt indicates that the SQL is a draft automatically generated, and the large model is required to carefully debug and modify the incorrect parts. In this mode, the LLM tends to actively find various potential defects and propose modification schemes; (2) Guided mild review mode: when the preliminary SQL structure is basically correct and may only have minor flaws, the prompt information emphasizes that the LLM should carefully check the SQL as a reviewer, and if there is no problem, the result remains unchanged, and if necessary, make as small adjustments and optimizations as possible. This mode guides the LLM to conduct a mild review of the SQL, avoiding excessive modification of the query that is basically correct.

[0042] Through the above dual-mode prompt strategy, comprehensive optimization and the need to avoid excessive modification can be considered for queries of different difficulties.

[0043] Subsequently, the system sends the constructed complete prompt to the selected large language model service (supporting multiple open source models) through the interface, requests it to review the SQL according to the prompt content and give modification suggestions. To improve the reliability of the LLM output result, the random sampling temperature is usually set to a low value (such as close to 0) when calling, to reduce the randomness in the result, and the maximum output Token number is set according to the expected SQL length (to ensure that even complex queries can be output completely), and appropriate stop symbols (such as special markers or line breaks) are specified to indicate that the LLM should stop generating after outputting the modified SQL query, preventing it from outputting additional explanatory text. After receiving the prompt, the LLM will analyze and reason the preliminary SQL using the provided context information and the knowledge it has learned during training: in the defect-oriented mode, the LLM will actively examine the entire SQL, locate any grammatical or logical inconsistencies and make modifications, such as adding missing JOIN conditions, correcting misuse of aggregate functions, completing missing aliases, etc.; while in the mild review mode, the LLM will follow the order of the check points in the prompt and check each part of the SQL, and only make targeted small adjustments when obvious problems are found. If the LLM judges that the original SQL is completely correct, it may return the SQL as is or only make minor formatting adjustments. After this intelligent proofreading process, the LLM will give the modified SQL query in the output. To facilitate automatic extraction, the prompt usually requires the LLM to clearly label the final result (for example, starting with "Modified SQL:"). The system parses the modified SQL text from the LLM's output based on this (filtering out the explanatory notes that the model may have attached). As a further safeguard, the system can verify the modified SQL again on the database: if the execution is successful and the result is as expected, it is confirmed as the final output SQL query; if the execution still fails or the result is incorrect, the collaborative rollback mechanism is started, and the original generated preliminary SQL is prioritized as the final output. That is, when the LLM's modifications introduce new errors, the system will discard the LLM's result and return to using the model's original generated SQL query, ensuring that the overall system performance does not decrease due to additional modification steps. At the same time, for difficult queries that have problems but the LLM has not successfully modified, the system can record the case for future use in improving the prompt strategy or training the underlying model, to continuously optimize the performance and stability of the overall solution. Embodiment Two:

[0044] A system for generating SQL queries based on natural language questions, the SQL queries acting on a target database to obtain query results corresponding to the natural language questions, the system comprising a semantic understanding and representation module, a context-aware screening module, a decoupled SQL generation module, and an intelligent modification guarantee module. a semantic understanding and representation module configured to convert schema information of a target database and a natural language question into a semantic vector representation; a context-aware screening module configured to screen, based on the semantic vector representation, a set of reduced database schemas related to the SQL query through an attention mechanism; a decoupled SQL generation module configured to generate a SQL skeleton based on the natural language question, the set of reduced database schemas and preset database constraint information, and fill specific elements of the SQL skeleton to form a preliminary SQL query; an intelligent correction guarantee module configured to dynamically correct and verify the preliminary SQL query by using a large language model, and output a final SQL query. Embodiment Three:

[0045] The electronic device of the present application comprises a memory and a processor, the memory stores a computer program, and the processor is used to call and run the computer program stored in the memory to execute the method of any one of the above embodiments.

[0046] The computer readable storage medium of the present application stores a computer program, and the computer program is executed by a processor to realize the steps of the method of any one of the above embodiments.

[0047] The above is only a specific embodiment of the present application, but the protection scope of the present application is not limited thereto, any person skilled in the art can easily think of changes or replacements within the technical range disclosed by the present application, which should be covered within the protection scope of the present application.

Claims

1. A method for generating SQL queries based on natural language questions, wherein the SQL queries are applied to a target database to obtain query results corresponding to the natural language question, characterized in that, The method includes: The pattern information of the target database and the natural language question are transformed into semantic vector representations; Based on the semantic vector representation, a set of simplified database schemas related to SQL queries is selected through an attention mechanism; Based on natural language problems, a simplified set of database schemas, and preset database constraint information, an SQL structure skeleton is generated, and specific elements of the SQL structure skeleton are filled in to form a preliminary SQL query. The initial SQL query is dynamically corrected and validated using a large language model, and the final SQL query is output.

2. The method for generating SQL queries based on natural language questions according to claim 1, characterized in that, The specific method for converting the pattern information of the target database and the natural language question into a semantic vector representation includes: The complete pattern information of the target database, consisting of all table names and their respective column names, is concatenated with the natural language question to form a text input sequence composed of several words. This sequence is then input into a pre-trained language model for encoding to obtain the context representation of each word in the text input sequence. The context representation is then pooled to extract the global semantic vector corresponding to the natural language question and the initial representation vectors of each table and column in the target database.

3. The method for generating SQL queries based on natural language questions according to claim 2, characterized in that, The specific method for filtering a set of concise database schemas related to SQL queries based on the semantic vector representation and using an attention mechanism includes: A cross-encoder structure based on a context-aware attention mechanism is employed to enhance the context of tables and columns. The global semantic vector is interacted with the initial representation vectors of each table and column through attention interactions, resulting in enhanced table and column representations that incorporate problem context information. Table-column multi-head attention fusion processing is then applied to the enhanced table representations and their corresponding column representations to obtain a context-fused representation. Table relevance processing is performed on the enhanced table representations and context-fused representations to obtain table relevance scores. Based on these scores, a ranking and filtering process is conducted to obtain the Top-K1 candidate tables. For each column in the Top-K1 candidate tables, the corresponding enhanced column representations and context-fused representations are further processed to obtain column relevance scores. Finally, based on these scores, a ranking and filtering process is conducted to obtain the Top-K2 candidate columns for each table, forming a simplified database schema set.

4. The method for generating SQL queries based on natural language questions according to claim 3, characterized in that, The specific method for generating an SQL structure skeleton based on natural language problems, a simplified database schema set, and preset database constraint information, and then filling in the specific elements of the SQL structure skeleton to form a preliminary SQL query includes: The natural language problem, the simplified database schema set, and the preset database constraint information are processed by sequence arrangement and input into the generation model. The SQL structure skeleton is generated by adopting the skeleton priority strategy. The SQL skeleton structure is filled with specific elements including table name, column name, and constant value to obtain the preliminary SQL query.

5. The method for generating SQL queries based on natural language questions according to claim 4, characterized in that, The SQL structure skeleton includes SQL keywords and placeholders.

6. The method for generating SQL queries based on natural language questions according to claim 4, characterized in that, The generative model is a Seq2Seq model.

7. The method for generating SQL queries based on natural language questions according to claim 4, characterized in that, The specific method for dynamically correcting and validating the initial SQL query using a large language model to output the final SQL query includes: The expected error risk of the initial SQL is assessed, resulting in a prompt mode selection. When significant errors exist, a defect-oriented prompt template is constructed for the initial SQL, resulting in a large language model input prompt. When only minor optimization is required, a mild review prompt template is constructed for the initial SQL, resulting in a large language model input prompt. The large language model input prompt is then subjected to large language model inference processing to obtain a corrected SQL query. The corrected SQL query is then subjected to database execution verification. If verification fails, a rollback mechanism is triggered, and the final SQL query is output.

8. A system for generating SQL queries based on natural language questions, wherein the SQL queries are applied to a target database to obtain query results corresponding to the natural language question, characterized in that, The system includes a semantic understanding and representation module, a context-aware filtering module, a decoupled SQL generation module, and an intelligent correction and protection module. The semantic understanding and representation module is used to transform the pattern information of the target database and the natural language question into a semantic vector representation; The context-aware filtering module is used to filter out a set of simplified database patterns related to SQL queries based on the semantic vector representation and through an attention mechanism. The decoupled SQL generation module is used to generate an SQL structure skeleton based on natural language problems, a simplified database schema set, and preset database constraint information, and to fill in the specific elements of the SQL structure skeleton to form a preliminary SQL query. The intelligent correction and protection module is used to dynamically correct and verify the initial SQL query using a large language model, and output the final SQL query.

9. An electronic device, characterized in that, The electronic device includes a memory and a processor, the memory storing a computer program, and the processor being configured to invoke and run the computer program stored in the memory to perform the method as described in any one of claims 1 to 7.

10. A computer-readable storage medium storing a computer program, characterized in that, When the computer program is executed by a processor, it implements the steps of the method as described in any one of claims 1 to 7 above.

Citation Information

Cited By

  • Database sub-mode division-based txt-to-sql generation method

    CN121636549A

  • A txt-to-sql generation method based on database sub-pattern division

    CN121636549B

  • Network security Text-to-KQL query generation method and system based on mode screening and semantic verification and storage medium

    CN121764952A