Intelligent question and answer method, system and device based on SQL query and storage medium

CN122594464APending Publication Date: 2026-08-18INSPUR YUNZHOU (SHANDONG) IND INTERNET CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610736388.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-05-26
Publication Date
2026-08-18

AI Technical Summary

Technical Problem

意图识别能力不足:现有系统普遍采用单级意图分类机制,对所有用户请求不加区分地尝试SQL生成

Benefits of technology

一、在意图识别层面,实现计算资源的精细化适配与无效占用的显著降低

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122594464A_ABST
    Figure CN122594464A_ABST
Patent Text Reader

Abstract

The application relates to the technical field of artificial intelligence, and specifically provides an intelligent question and answer method, system, device and storage medium based on SQL query, which comprises the following steps: classifying user intention through a three-level discrimination mechanism to determine whether to execute database query; if the query is executed, the user request is decomposed into multiple atomic query tasks, the dependency relationship among the tasks is identified, and a directed acyclic graph is constructed; the atomic query tasks are prioritized, a task execution pipeline is generated according to the sorting result and the dependency relationship; a query statement is generated based on the task execution pipeline and is executed to obtain a query result; the query result is preprocessed and semantically enriched; and the processed query result is constructed into a structured prompt word by adopting a semantic hierarchical organization strategy, a general large language model is used to generate a natural language answer and the answer is output. The application significantly reduces the consumption of computing resources and response delay, and improves the SQL generation accuracy and answer readability in a complex query scene.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of artificial intelligence technology, specifically relating to an intelligent question-answering method, system, device, and storage medium based on SQL queries. Background Technology

[0002] Natural Language to SQL (NL2SQL) technology aims to help non-technical users easily query databases using natural language. Current mainstream solutions fall into two categories: one is the traditional semantic parsing method, which uses templates or sequence models to convert user questions into single SQL statements and returns the results in tabular form; the other is an end-to-end method based on large language models, which directly generates SQL or answers through prompt word engineering.

[0003] However, all of the above solutions have the following technical drawbacks: Insufficient intent recognition capability: Existing systems generally adopt a single-level intent classification mechanism, attempting SQL generation indiscriminately for all user requests. On the one hand, explicit non-query requests (such as greetings and system operations) cannot be quickly bypassed, resulting in wasted computing resources and response delays; on the other hand, fixed threshold judgments are rigid and cannot adapt to scenarios such as information omission and reuse of references in multi-turn dialogues, and lack the ability to learn from user feedback, making it difficult to continuously optimize classification performance. In addition, query and non-query intents overlap in the semantic space, limiting the accuracy of single classification decisions.

[0004] Weak Complex Query Processing Capabilities: For complex queries with multiple intents and operational steps, existing methods lack the ability to decompose and orchestrate tasks. Directly generating a single SQL statement can easily lead to logical errors and low execution efficiency. Furthermore, query results are returned only in raw data form, requiring users to interpret the table information themselves. This disconnect between the answer generation and data query stages, coupled with a lack of structured organization and semantic enrichment tailored to cognitive habits, makes it difficult to transform "data" into "insights."

[0005] In summary, how to achieve refined intent-based layered filtering and dynamic adaptive judgment of user requests in intelligent question-answering systems to reduce the invalid occupation of computing resources by non-query requests and shorten the response latency of invalid requests, and on this basis, perform semantic-level decomposition, dynamic scheduling, and knowledge-based reconstruction of results for complex query tasks to reduce database execution overhead, optimize query performance, reduce user cognitive costs and interaction rounds, thereby achieving efficient resource utilization and improved response efficiency across the entire chain, is a technical problem that urgently needs to be solved in this field. Summary of the Invention

[0006] In view of the above-mentioned shortcomings of the prior art, the present invention provides an intelligent question-answering method, system, device and storage medium based on SQL query to solve the above-mentioned technical problems.

[0007] In a first aspect, the present invention provides an intelligent question-answering method based on SQL queries, comprising: Upon receiving a user request, the user request is classified into intents using a three-level discrimination mechanism to determine whether to execute a database query. In response to executing a database query, the user request is decomposed into multiple atomic query tasks, and the dependencies between the atomic query tasks are identified. The atomic query tasks are prioritized, and a task execution pipeline is generated based on the prioritization results and dependencies. Based on the task execution pipeline, the corresponding SQL query statement is generated and executed to obtain the query result, and the query result is subjected to data preprocessing and semantic enrichment processing. A semantic hierarchical organization strategy is adopted to construct structured prompts from the processed query results. These structured prompts are then input into a general large model to generate and output natural language answers.

[0008] In an optional implementation, the user request is classified into intents using a three-level discrimination mechanism to determine whether the user request is a database query intent, including: In the first-level discrimination stage, based on the preset non-query intent rule library, the user request is matched with keywords or regular expressions; if any rule in the non-query intent rule library is matched, it is directly determined to be a non-database query intent, and the intent classification process is terminated. In the second-level discrimination stage, in response to the user request not being determined as a non-database query intent in the first level, the syntactic features, semantic vector similarity features, and domain entity link features of the user request are extracted, and the extracted features are input into the query intent classification model to output the query probability score that the user request belongs to the database query intent. In the third-level discrimination stage, a preset benchmark threshold is used to compare the query probability score with the benchmark threshold; when the query probability score is greater than or equal to the benchmark threshold, it is determined to be a database query intent; when the query probability score is less than the benchmark threshold, it is determined to be a non-database query intent.

[0009] In an optional implementation, the method further includes a threshold adaptive adjustment mechanism: When there is a previous database query request in the previous context of this dialogue round, and the current user request contains an abbreviated instruction, the value of the baseline threshold will be temporarily reduced to adapt to the information sparsity of the current request. In response to a user's correction operation on the query result, misjudgment cases caused by incorrect intent classification are identified from the correction operation, and the misjudgment rate is calculated according to a preset period. When the misjudgment rate is higher than a first preset threshold, the baseline threshold is increased. When the misjudgment rate is lower than a second preset threshold, the baseline threshold is decreased. The baseline threshold is taken as an initial value when there is no temporary adjustment.

[0010] In an optional implementation, in response to executing a database query, the user request is decomposed into multiple atomic query tasks, and the dependencies between the atomic query tasks are identified, including: The user request is subjected to dependency parsing and semantic role labeling to generate a syntactic dependency tree with words as nodes and dependency relations as edges. Core predicates, argument structures and modifiers are extracted from the syntactic dependency tree. Based on the syntactic dependency tree and semantic role labeling results, each predicate-argument combination or modification-qualifying structure with independent query semantics in the user request is identified as an operation unit; a unique identifier is assigned to each operation unit, and the one or more word nodes covered by the operation unit in the syntactic dependency tree and their position information are recorded; Each operation unit is mapped to an atomic query task. The mapping rule is as follows: based on the core predicate and argument type of the operation unit, a preset task type template is matched. The task type template includes one or more of the following: conditional filtering task, aggregation calculation task, sorting operation task, grouping aggregation task, multi-table association task, and limited output task. The mapped atomic query task is encapsulated into an independent task object. Each task object contains a task type, a set of related word nodes, and parameter information extracted from the operation unit. Traverse the syntactic dependency tree and identify the explicit associations between the word node sets corresponding to the atomic query tasks based on the following syntactic dependency features: dependency edge type, conjunctions, punctuation marks, and order adverbs. Based on the explicit associations, generate parallel relationships, sequential dependencies, or nested inclusion relationships between the atomic query tasks, and label the pre-task set and post-task set of each task accordingly. For atomic query tasks that do not establish associations through explicit dependency identification, implicit dependencies are identified based on data dependencies, semantic dependencies, and domain knowledge; the identified implicit dependencies are then added to the pre-task set and post-task set of each task. Using atomic query tasks as nodes and the dependencies defined in the pre-task set and post-task set as directed edges, an initial directed graph is constructed; the initial directed graph is topologically sorted and verified, and if a circular dependency is detected, a conflict resolution strategy is triggered until a directed acyclic graph is generated. The final verified directed acyclic graph is used as the dependency representation for the atomic query task.

[0011] In an optional implementation, the atomic query tasks are prioritized, and a task execution pipeline is generated based on the prioritization results and dependencies, including: Priority scores for each task are calculated by weighting and summing semantic tightness, dependency, execution cost, and historical weights. In response to user emphasis, apply a positive increment to the priority score of the emphasized task; in response to database load exceeding the threshold, apply a negative decay to the priority score of high-cost tasks. Sort tasks in descending order of priority and perform topology rearrangement based on the directed acyclic graph of dependencies; mark adjacent tasks with no dependencies and similar priorities as parallel groups to generate a task execution pipeline that includes both serial order and parallel strategies.

[0012] In an optional implementation, a corresponding SQL query statement is generated and executed based on the task execution pipeline to obtain query results. The query results are then subjected to data preprocessing and semantic enrichment, including: The task execution pipeline, database table structure, and user requests are integrated into hierarchical prompt words, which are then input into a large language model to generate SQL query statements that conform to task priorities. For complex queries, a progressive execution strategy is adopted, which decomposes them into multiple subqueries and executes them step by step; intermediate results of high-priority tasks are cached; in response to the failure of a subtask, its priority is automatically reduced and the pipeline is rescheduled. Identify the data type of the query results and adopt the corresponding integration strategy; extract key indicators including maximum value, minimum value, and trend characteristics; detect and mark abnormal data points; Comparison relationships between labeled data; add relative time context descriptions to time series data.

[0013] In an optional implementation, a semantic hierarchical organization strategy is used to construct structured prompts from the processed query results, including: Identify the intent type of the user request and match the data organization logic corresponding to the intent type from a preset narrative structure template library; the intent type includes statistical analysis, detailed query, comparative analysis, and exploration and discovery; the narrative structure template includes general-to-specific structure, time or logical order structure, comparison structure, and question-evidence structure. A three-level semantic hierarchy is generated through a dynamic hierarchical construction algorithm. The three-level semantic hierarchy includes: Core summary layer: extracting no more than a preset number of key conclusions or core indicators from the query results; Detailed analysis layer: grouping and summarizing the query results according to one or more data dimensions to generate structured analysis content; Original data citation layer: selectively retaining representative or supporting detailed data entries from the query results. The content of the three semantic levels is filled into the corresponding variable slots of the selected narrative structure template, and the selection of the connecting word library is adjusted according to the preset style adjustment parameters to generate structured prompt words with natural language coherence.

[0014] Secondly, the present invention provides an intelligent question-answering system based on SQL queries, comprising: The intent determination module is used to receive user requests and classify the intent of the user requests through a three-level discrimination mechanism to determine whether to execute a database query. The task construction module is used to decompose the user request into multiple atomic query tasks in response to the execution of a database query, and to identify the dependencies between the atomic query tasks. The task sorting module is used to prioritize the atomic query tasks and generate a task execution pipeline based on the sorting results and dependencies. The query processing module is used to generate and execute corresponding SQL query statements based on the task execution pipeline, obtain query results, and perform data preprocessing and semantic enrichment on the query results. The answer generation module is used to construct structured prompts from the processed query results using a semantic hierarchical organization strategy, input the structured prompts into a general large model, generate natural language answers, and output them.

[0015] Thirdly, a device is provided, comprising: Memory is used to store intelligent question-answering programs based on SQL queries; The processor is configured to implement the steps of the SQL query-based intelligent question-answering method provided in the first aspect when executing the SQL query-based intelligent question-answering program.

[0016] Fourthly, a computer-readable storage medium is provided, on which an intelligent question-answering program based on SQL queries is stored, wherein when the intelligent question-answering program based on SQL queries is executed by a processor, the steps of the intelligent question-answering method based on SQL queries provided in the first aspect are implemented.

[0017] The intelligent question-answering method, system, device, and storage medium based on SQL queries provided by this invention have the following beneficial effects: I. At the intent recognition level, achieve fine-grained adaptation of computing resources and significantly reduce invalid usage. This application employs a three-tiered discrimination mechanism for layered filtering and dynamic threshold determination of user requests. The shallow, fast filtering layer, based on a lightweight rule base, can accurately bypass explicit non-query requests such as greetings and system operation commands on a microsecond-level timescale, preventing these requests from mistakenly entering the large model inference or SQL generation chain, significantly reducing wasted computing resources and response latency. The deep semantic parsing layer and the dynamic threshold decision layer work together to achieve context-aware adaptive determination for semantically ambiguous and information-sparse multi-turn dialogue requests, reducing retry interactions and invalid calculations caused by misjudgments. Experimental data shows that in hybrid dialogue scenarios, this application reduces the resource consumption of non-query requests and improves system throughput compared to traditional single-level intent classification schemes.

[0018] Second, at the query generation level, achieve logical optimization and a leap in execution efficiency for complex query tasks. This application abandons the traditional "one-step" SQL generation paradigm and pioneers an atomic task decomposition and dependency identification mechanism. It breaks down complex user requests into atomic query tasks with single responsibilities and explicitly expresses the logical constraints between tasks through a directed acyclic graph. Based on this, it introduces a multi-task priority ranking and dynamic scheduling strategy, intelligently ranking atomic tasks according to multi-dimensional factors such as semantic tightness, dependency, and execution cost, generating a pipelined solution that conforms to logical order and supports parallel execution. This effectively avoids problems such as logical errors, Cartesian products, and index failures caused by the lack of intermediate representations in traditional methods, significantly reducing the burden on the database optimizer and the overhead of the execution engine. In actual tests, this application reduces SQL execution time by an average of 35% to 50% in complex query scenarios such as multi-table joins, nested aggregations, and mixed sorting, while significantly reducing memory and I / O consumption.

[0019] Third, at the level of answer presentation, achieve a leap in cognitive efficiency from "data output" to "insight delivery". This application breaks through the shallow interaction mode of existing systems that simply output tables, by preprocessing query results, enriching their semantics, and reconstructing their hierarchical narrative structure. By identifying user intent types (statistical analysis, comparative analysis, trend insights, etc.), it dynamically matches narrative templates, transforming structured data into three levels of semantic prompts containing core summaries, dimensional analysis, and key evidence. These prompts are then input into a general model to generate natural language answers that conform to human cognitive habits. This significantly reduces the time cost and cognitive burden for users interpreting raw data, compressing the information acquisition process—which traditionally requires multiple follow-up questions and secondary processing—into a single-round interactive loop. User testing feedback indicates that the efficiency of obtaining answer information generated by this application is improved by over 60%, and user satisfaction is improved by 45%.

[0020] IV. At the end-to-end collaboration level, achieve a dual benefit of end-to-end resource efficiency and system robustness. This application organically couples four core modules—intent filtering, task decomposition, dynamic scheduling, and semantic reconstruction—to form an intelligent pipeline from "user request input" to "exploratory answer output." Through engineering mechanisms such as progressive execution, error backtracking and degradation, and intermediate result caching, it effectively addresses performance fluctuations and resource contention in scenarios with high concurrency, large data volumes, and complex query boundaries. Compared to existing NL2SQL systems, this application supports 1.8 times more concurrent requests with the same hardware configuration, reduces long query timeout rates by 70%, and achieves a smoother system resource utilization curve, demonstrating significant advantages for industrial deployment.

[0021] In summary, this application achieves triple savings in computing resources, database resources, and user cognitive resources through systematic innovation across the entire chain of "intent recognition - task orchestration - data reconstruction". It solves the common problems of resource mismatch, efficiency bottlenecks, and experience gaps in existing intelligent question answering systems in mixed scenarios, and has strong advanced features and industrial promotion value. Attached Figure Description

[0022] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, for those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0023] Figure 1 This is a schematic flowchart of a method according to an embodiment of the present invention.

[0024] Figure 2 This is another illustrative flowchart of a method according to an embodiment of the present invention.

[0025] Figure 3 This is a schematic flowchart illustrating the three-level discrimination mechanism of a method according to an embodiment of the present invention.

[0026] Figure 4 This is a schematic block diagram of a system according to an embodiment of the present invention.

[0027] Figure 5 This is a schematic diagram of the structure of a device provided in an embodiment of the present invention. Detailed Implementation

[0028] To enable those skilled in the art to better understand the technical solutions of this invention, the technical solutions of the embodiments of this invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this invention, and not all embodiments. Based on the embodiments of this invention, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of this invention.

[0029] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this invention pertains. The terminology used herein in the description of the invention is for the purpose of describing particular embodiments only and is not intended to be limiting of the invention.

[0030] The SQL query-based intelligent question-answering method provided in this embodiment of the invention is executed by a computer device, and correspondingly, the SQL query-based intelligent question-answering system runs on the computer device.

[0031] Figure 1 This is a schematic flowchart illustrating a method according to an embodiment of the present invention. Wherein, Figure 1 The executing entity can be an intelligent question-and-answer system based on SQL queries. Depending on different needs, the order of the steps in this flowchart can be changed, and some can be omitted.

[0032] like Figure 1 As shown, the method includes: S1. Receive a user request and classify the user request by intent through a three-level discrimination mechanism to determine whether to execute a database query; S2. In response to executing a database query, the user request is decomposed into multiple atomic query tasks, and the dependencies between the atomic query tasks are identified; S3. Prioritize the atomic query tasks and generate a task execution pipeline based on the sorting results and dependencies; S4. Generate and execute the corresponding SQL query statement based on the task execution pipeline to obtain the query result, and perform data preprocessing and semantic enrichment processing on the query result; S5. Using a semantic hierarchical organization strategy, the processed query results are constructed into structured prompts. The structured prompts are then input into a general large model to generate natural language answers and output them.

[0033] Please refer to Figure 2 The steps of the present invention will be described in detail below.

[0034] In one embodiment of the present invention, based on step S1, the following will provide a possible embodiment and describe its specific implementation in a non-limiting manner.

[0035] like Figure 3 As shown, after receiving a user request, it sequentially enters the shallow fast filtering layer, the deep semantic parsing layer, and the dynamic threshold decision layer for processing.

[0036] The shallow, fast filtering layer pre-builds a rule base for non-query intents, which contains three types of rule templates: (1) System operation type: regular expression patterns such as "^Logout$", "^Refresh page$", "^Clear cache$", etc.; (2) General Q&A type: Keyword sets such as {"Hello", "Hello", "Help", "Document", "Tutorial"} and combination patterns; (3) Explicit irrelevant instruction class: domain blacklist words such as “weather”, “stock”, “news”, etc., which are external query terms that are irrelevant to the current database domain.

[0037] The system uses a Trie tree to accelerate multi-pattern matching, performing a linear scan of user requests. Let the user request be string Q, and the non-query intent rule base be R={r1,r2,...,r...}. n}.like Make r i If Q is matched, it is immediately determined that it is not a database query intent, the subsequent process is terminated, and the request is directly routed to the general large model.

[0038] Example: A user inputs "Hello, can you help me check some data?" The rule base matches the general question-and-answer rule for "Hello," so it's bypassed and doesn't enter the SQL generation process. Actual testing shows a single match takes less than 50μs, saving 99.8% of computational overhead compared to traditional complete semantic parsing solutions.

[0039] If a request does not match a rule in the first layer, it proceeds to this layer for fine-grained semantic analysis. This layer extracts three types of features: (1) Grammatical features F syn Dependency parsing tools (such as LTP and Stanford Parser) are used to parse user requests and extract the following binary features: Does it contain database operation keywords: {query, statistics, summation, average, sorting, grouping, filtering, screening}? Whether it contains suspected field names / table names: by performing a fuzzy match with field comments and table comments in the database metadata; Does it contain quantifiers, time terms, or comparison operators?

[0040] (2) Semantic vector similarity feature F sem The user request Q is encoded into a 768-dimensional vector v using a Sentence-BERT pre-trained model. Q A pre-built "typical query template library" T={t1,t2,...,t m}, each template t j It corresponds to a type of query pattern (such as "query [field] from [table]" or "aggregate under [statistical conditions]") and pre-computes the template vector. .

[0041] Calculate the cosine similarity between the user request vector and each template vector, and take the maximum value as the semantic similarity feature: (3) Domain entity linking feature F ent Extract all noun phrases from the user request and link them to table names, field names, and their comments in the database metadata. Calculate the matching degree between the noun phrases and metadata items using Jaccard similarity. If a successful link to any table / field is established and the similarity is higher than a threshold (e.g., 0.6), then F... ent =1, otherwise F ent =0.

[0042] The above features are concatenated into a feature vector x=[F syn ,F sem ,F ent The input is fed into the pre-trained LightGBM binary classification model, and the output query probability score P∈[0,1] represents the probability that the user's request belongs to the database query intent.

[0043] Preset baseline threshold (Initial value set to 0.6), and the query probability score P is compared with the current judgment threshold. Comparison:

[0044] Among them, the judgment threshold The value is taken as follows when there is no temporary adjustment. It is dynamically updated through a threshold adaptive adjustment mechanism.

[0045] In addition, the judgment threshold Perform adaptive adjustments: First, maintain the state variable C of the current dialogue session, recording whether the preceding request was a database query. A temporary threshold reduction is triggered when the following two conditions are met: (1) The preceding request is determined to be a database query intent; (2) The current user request is identified by dependency parsing as having omitted references, including but not limited to: Demonstrative pronouns: "this", "that", "same as above", "should", "its"; Empty object: "Check again", "Continue", "Anything else?"; The predicates are omitted: "What about last year?" "What about the department?".

[0046] Temporarily adjusted judgment threshold The calculation formula is:

[0047] in: This is the attenuation coefficient, empirically taken as 0.3~0.5; This is an omission factor, ranging from 0.5 to 1.0 depending on the specificity of the omitted reference (e.g., 1.0 for "same as above", 0.7 for "this", and 0.8 for "last year?"). This temporary adjustment only applies to the current request round; it automatically reverts to the baseline threshold in the next round. .

[0048] Example: In the first round, a user asks, "What were the sales figures for each department in 2023?" which is determined to be a query. In the second round, the user enters, "What about 2024?". The system recognizes "What about...?" as an abbreviated structure and temporarily lowers the threshold from 0.6 to 0.6 × (1 - 0.4 × 0.8) = 0.408. This ensures that even if the query probability score P = 0.55 (lower than the original threshold of 0.6) in this round of requests due to information sparsity, it can still be correctly determined as a query intent.

[0049] Secondly, record user interactions with the generated SQL results. When a user manually corrects the generated SQL statement (such as changing field names, adding conditions, or rewriting JOIN logic) and executes it successfully, mark this interaction as a potential misjudgment case.

[0050] Define the types of misjudgments: False negative (FN): What should have been a database query was judged as a non-query (the user subsequently initiated a similar query). False positive (FP): A query that should have been identified as a non-database query is identified as a query (the user corrects the SQL or directly rejects the answer).

[0051] The false positive rate is calculated over a fixed period T (e.g., 24 hours or every 1000 requests): in, This represents the number of requests that actually had database query intent within the period. This refers to the number of requests that were actually not queries but were classified as queries by the system. This refers to the number of requests that were actually queries but were classified as non-queries by the system. This represents the number of requests within the period that were not actually intended to query the database. This represents the total number of requests received within the period.

[0052] Using the overall misclassification rate E as the feedback signal, in practical engineering implementation, it is simplified to a piecewise linear adjustment strategy:

[0053] Where: E high =5%, E low =2% is the business experience threshold; Δ up =0.02, Δ down =0.01 is the step size; It is restricted to the range of [0.3, 0.8] to avoid excessive deviation.

[0054] Example: Initial setup of a business system upon launch =0.6. After one week of operation, the statistical false positive rate E=6.8%, which is higher than E. high The system automatically raised the baseline threshold to 0.62. After two more weeks of operation, the false positive rate dropped to 4.2%, and the threshold stabilized in the range of 0.61 to 0.62, achieving a dynamic balance between intent classification accuracy and recall.

[0055] In actual operation, the final value of the decision threshold θ is: This design achieves agile contextual response at the micro-interaction level and continuous performance optimization at the macro-operation level, solving the inherent defect of the traditional fixed threshold mechanism in dynamic environments that "one-size-fits-all".

[0056] If it is determined that the user's intent type does not require a database query, then the user intent is directly routed to the general large model interface.

[0057] In one embodiment of the present invention, based on step S2, the following will provide a possible embodiment and describe its specific implementation in a non-limiting manner.

[0058] Suppose we receive a user request: "Calculate the total salary of each department in 2023, sort in descending order, and select the top 3." The following example will illustrate the data processing flow and implementation methods step by step.

[0059] Step S201: Syntactic and Semantic Analysis First, dependency parsing and semantic role labeling are performed on the user request text. Specifically, a deep learning-based Chinese dependency parsing tool (such as LTP, HanLP, or Stanford Parser) is used to parse the input sentence into a syntactic dependency tree with words as nodes and dependency relations as edges. Dependency relation types include subject-verb, verb-object, attributive-head, adverbial-head, and coordinate relations.

[0060] Simultaneously, semantic role labeling is performed based on the dependency syntax tree to identify the argument structure governed by each core predicate. Argument roles include agent, patient, time, place, manner, quantity, comparison, etc. Through the above analysis, three types of key information are extracted from the sentence: core predicates (such as "statistics", "sorting", "take"), argument structure (such as "total salary" as patient, "2023" as time, and "each department" as scope), and modifying elements (such as "descending order" as manner and "top 3" as quantity limitation).

[0061] In this example, three core predicates were identified: “statistics”, “sorting”, and “taking”; and the corresponding arguments and modifiers were extracted: “2023” is the time argument, “departments” is the scope argument, “total salary” is the patient argument, “descending order” is the manner modifier, and “top 3” is the quantity modifier.

[0062] Step S202: Operation Unit Identification and Packaging Based on the syntactic dependency tree and semantic role labeling results generated in step S201, each predicate-argument combination or modification / qualification structure with independent query semantics in the user request is identified as an operation unit. The division of operation units follows these rules: each core predicate and its directly governed arguments constitute an independent operation unit; each parallel branch in a parallel structure constitutes an independent operation unit; in a nested structure, the inner modification / qualification is separated from the outer predicate, constituting an independent operation unit; in a comparison structure, the comparison benchmark and the comparison result each constitute an independent operation unit.

[0063] For this example, five operational units were identified: the first operational unit corresponds to "statistical total salary", consisting of the core predicate "statistical" and the patient argument "total salary"; the second operational unit corresponds to "time condition 2023", consisting of the time argument "2023" and its implicit filtering semantics; the third operational unit corresponds to "grouping condition each department", consisting of the scope argument "each department" and its implicit grouping semantics; the fourth operational unit corresponds to "descending order sorting", consisting of the core predicate "sorting" and the manner modifier "descending order"; and the fifth operational unit corresponds to "taking the top 3", consisting of the core predicate "taking" and the quantity modifier "top 3".

[0064] Each operation unit is assigned a globally unique identifier, and the one or more word nodes covered by the operation unit in the syntactic dependency tree and their start and end positions in the original sentence are recorded for subsequent tracing and alignment.

[0065] Step S203: Atomic query task mapping and encapsulation A pre-built template library of atomic query task types covers six core query operations: conditional filtering tasks, aggregation calculation tasks, sorting operation tasks, grouping aggregation tasks, multi-table join tasks, and output restriction tasks. Each task template defines the matching conditions and output parameter structure.

[0066] Iterate through each operation unit and execute the following mapping logic: First, extract the core predicate and argument type of the operation unit; then calculate the semantic similarity between the operation unit and each task template. The similarity calculation is based on pre-trained domain word vectors or a thesaurus; finally, select the template with the highest similarity and exceeding the preset threshold for instantiation, and extract the parameter information required by the template from the operation unit.

[0067] In this example, the five operation units are mapped to five atomic query tasks: The first operation unit, "Calculate Total Salary", is mapped to an aggregation calculation task, with the parameters being the aggregation function "SUM" and the aggregation field "Salary". The second operation unit, "Time Condition 2023", is mapped to a conditional filtering task, with parameters being the field "Year", the operator "equal to", and the value "2023". The third operation unit, "Grouping conditions for each department," is mapped to a grouping aggregation task, with the parameter being the grouping field "department." The fourth operation unit, "descending order sorting", is mapped to a sorting operation task, with the parameters being the sorting field "total salary" and the sorting direction "descending". The fifth operation unit, "Take the top 3", is mapped to a limited output task with parameters of offset "0" and row number "3".

[0068] Each atomic query task is encapsulated as an independent task object, which contains a task type identifier, a set of associated word nodes, structured parameter information, and raw text fragments, providing a data foundation for subsequent dependency identification and priority ranking.

[0069] Step S204: Explicit Dependency Identification Traverse the syntactic dependency tree generated in step S201 and identify the explicit associations between the word node sets corresponding to the atomic query tasks based on syntactic dependency features. The syntactic dependency features include: dependency edge types (such as parallel relations, adverbial-head relations, and attributive-head relations), conjunctions (such as "and", "and", and "then"), punctuation marks (such as semicolons and commas), and order adverbs (such as "first", "second", and "last").

[0070] Based on the above characteristics, three types of explicit associations are generated: Parallel relationship: If the word node sets corresponding to two tasks have parallel dependency edges or are connected by parallel conjunctions, they are determined to be in a parallel relationship and are independent of each other; Sequential dependency: If the word node corresponding to task A is an adverbial modifier of the word node corresponding to task B, then task A is determined to depend on task B, that is, task A must be executed before task B. Nested inclusion relationship: If the word node corresponding to task A is a modifier of the word node corresponding to task B, then task A is determined to be nested inside task B, and should be treated as a sub-condition of task B during execution.

[0071] Based on the identified explicit relationships, each atomic query task is labeled with a set of preceding and following tasks. In this example, the syntactic dependency tree shows that "2023" is a time adverb for "statistics," so the time filtering task is labeled as a preceding task for the aggregation calculation task; "departments" is a scope modifier for "statistics," so the grouping aggregation task is labeled as a preceding task for the aggregation calculation task; and "descending order" is a manner adverb for "sorting," so the sorting operation task is labeled as a preceding task for the output-limiting task.

[0072] Step S205: Implicit Dependency Identification For atomic query tasks that do not establish explicit associations through step S204, implicit dependencies are further identified based on data dependencies, semantic dependencies, and domain knowledge.

[0073] At the data dependency level, the dependencies between fields and tables involved in atomic tasks are analyzed by querying database metadata. For example, if the parameter field of task B is the output calculation result of task A, then task A is determined to be a prerequisite task for task B; if task A involves a main table and task B involves a subordinate table and needs to be related through a foreign key, then task A is determined to be executed before task B.

[0074] At the semantic dependency level, logical order is inferred based on deep semantic role relationships. For example, the tasks corresponding to predicates that express results such as "get", "generate", and "calculate" depend on tasks that express causes, methods, or conditions; tasks that express methods or tools depend on tasks that express purposes.

[0075] At the domain knowledge level, dependency completion is performed using a pre-built SQL execution order rule base. This rule base encapsulates general experience in database query optimization, such as: conditional filtering tasks take precedence over aggregation calculation tasks; grouping aggregation tasks take precedence over aggregation calculation tasks; aggregation calculation tasks take precedence over sorting operations; and sorting operations take precedence over output restriction tasks.

[0076] In this example, there is no explicit syntactic association between the aggregation task and the sorting task. However, the domain knowledge "aggregate first, then sort" triggers implicit dependency recognition, marking the aggregation task as a prerequisite task for the sorting task. Similarly, although the conditional filtering task and the grouping aggregation task are explicitly associated with the aggregation task, they have no direct dependency on each other. Based on data independence, they are determined to be tasks that can be executed in parallel, and no dependency edges need to be added.

[0077] All identified implicit dependencies are added incrementally to the pre-task and post-task sets of each task, without overwriting existing explicit dependencies.

[0078] Step S206: Dependency Graph Construction and Verification Using atomic query tasks as nodes and the dependencies defined in the preceding tasks as directed edges, an initial directed graph is constructed. The direction of the directed edges is uniformly from the preceding task to the following task to ensure the consistency of dependency semantics.

[0079] After construction, a topological sorting check is performed on the initial directed graph. If a topological sequence containing all nodes can be output, it proves that there are no cycles in the graph, and we can proceed directly to the next step; if a circular dependency is detected (i.e., a cycle exists in the graph), the preset conflict resolution strategy is triggered.

[0080] Conflict resolution strategies should be tried in the following order of priority: First priority: Task type priority. A standard execution order for various built-in tasks is established (e.g., filtering tasks take precedence over aggregation tasks, sorting tasks take precedence over limiting tasks), retaining dependency edges that conform to this order and disconnecting reverse edges; Second priority: Confidence of dependency source. Explicit dependencies (based on syntactic features) have higher confidence than implicit dependencies (based on rule inference), so explicit dependency edges are retained first. Third priority: Semantic rationality. Based on the linear order of operation units in natural sentences, retain dependency edges that conform to word order intuition; Fourth priority: Historical execution logs. Query historical execution plans for similar queries and use the dependency direction that appears more frequently. Fifth priority: Default disconnect. If none of the above strategies can make a decision, randomly disconnect an edge and log it for subsequent manual review or model tuning.

[0081] The resolution operation is performed iteratively until a directed acyclic graph is generated. In this example, the initial directed graph has been topologically sorted and verified to have no cyclic dependencies, thus passing the verification directly.

[0082] Step S207: Output the dependency expression The final validated directed acyclic graph is used as the dependency representation of the atomic query tasks and output to the downstream multi-task sorting module. This dependency graph fully depicts the logical constraints between all atomic query tasks, including the following core information: a complete list of tasks, task types and parameters, a set of dependency edges between tasks, and a valid topology execution sequence.

[0083] The final topology execution sequence generated in this example is as follows: first, the conditional filtering task and the grouping aggregation task are executed in parallel; then, the aggregation calculation task is executed; next, the sorting operation task is executed; and finally, the limited output task is executed. This sequence conforms to the semantic logic of the user request and also follows the general principles of database query optimization.

[0084] In one embodiment of the present invention, based on step S3, the following will provide a possible embodiment and describe its specific implementation in a non-limiting manner.

[0085] S301. Calculate a priority score for each atomic query task. This score is obtained by a weighted sum of four factors. The weight coefficients can be preset or dynamically configured according to the business scenario. In this embodiment, fixed weights are used, and the weight vector is (α,β,γ,δ) = (0.4, 0.3, 0.2, 0.1). The definitions and calculation methods of each factor are as follows: Semantic tightness measures the strength of the association between the atomic query task and the core intent of the user's request. The system calculates this in two ways: Keyword overlap: The proportion of keywords in the original text fragment of the atomic query task, after removing stop words from the user request, to the total length of the keyword set K. If the task has no explicit text fragment (such as a task generated by implicit dependency), then the value is 0.

[0086] Semantic vector similarity: Using Sentence-BERT to encode the entire user request into a vector v query The task type name and parameters are concatenated into a text description and encoded into a vector v. task Calculate the cosine similarity.

[0087] Finally, the weighted average of the two (each weight is 0.5 in this embodiment) is taken as the semantic tightness score, with a value range of [0,1].

[0088] Dependency, this factor reflects the degree to which a task is depended upon by other tasks. A higher dependency indicates that the task is fundamental to subsequent tasks and should theoretically be executed first. The calculation formula is:

[0089] Where |PreTasks(t)| is the number of pre-tasks of task t, and |TotalTasks| is the total number of atomic tasks decomposed from the current request. The larger this value, the fewer the task dependencies, and the higher it should be executed.

[0090] Execution cost, this factor estimates the resource overhead required to execute the task in the database. The system obtains cost estimates in the following ways: For conditional filtering tasks: estimate the number of rows to scan and the cost based on the index status of the filtering field, the cardinality of the field's unique values, and the selectivity of the filtering values.

[0091] For aggregation calculation tasks: estimate the grouping calculation cost based on the cardinality of the grouping field and the data distribution of the aggregation field.

[0092] For sorting operations: Estimate the sorting cost based on the amount of data to be sorted and whether an index is covered.

[0093] For tasks with limited output: the cost is extremely low, so set it to a fixed minimum value.

[0094] The cost estimates for all tasks are normalized to the [0,1] range using maximum and minimum values ​​to obtain a cost score. The execution cost factor is 1 minus the cost score, meaning the lower the cost, the higher the priority.

[0095] Historical weighting utilizes user interaction feedback to reflect the frequency with which users mark similar tasks as "important." The system maintains a task type-importance weight mapping table. Whenever a user gives a positive evaluation of the generated SQL or answer (e.g., "This is exactly what I wanted") or explicitly emphasizes a certain type of operation, the importance weight of the corresponding task type increases; conversely, if a user expresses dissatisfaction with a certain type of operation or manually removes it, the importance weight decreases. The historical weighting factor is set to the current weight value of that type of task in the mapping table, initialized to 0.5, with a value range of [0.2, 0.8].

[0096] The priority score calculation formula is as follows:

[0097] Where SR(t) is the semantic tightness, Cost(t) is the normalized execution cost estimate, HW(t) is the historical weight, and N is the total number of tasks.

[0098] S302. Based on the baseline priority score, dynamically adjust according to the real-time dialogue context and system operating status to enhance scenario adaptability.

[0099] In each round of dialogue, monitor whether the user gives an emphatic statement for a specific query operation. The criteria for identifying emphatic statements include: explicit emphatic words: such as "pay attention to", "prioritize", "focus on", "first...then...", etc.; comparative and superlative degrees: such as "most important", "highest", "most critical"; repeated mention: the user mentions the same field or operation multiple times in multiple rounds of dialogue; sentiment: identify positive emphasis through sentiment analysis of user feedback statements.

[0100] When a user's emphasis is detected on a particular atomic query task (or its corresponding fields or operations), a positive increment is applied to the priority score of that task. The increment is calculated using an adjustable enhancement coefficient.

[0101] Here, λ is the emphasis intensity factor, which takes a value between 0.1 and 0.3 depending on the explicitness of the emphasized statement. This design ensures that the priority score is limited to the [0,1] interval, avoiding overflow.

[0102] Real-time collection of database performance metrics, including CPU utilization, IO wait time, active connections, and slow query count, is used to generate a load index L (range 0-1). When the load index L exceeds a preset threshold L0... threshold When the value is 0.7 in this embodiment, the high-cost task degradation strategy is triggered.

[0103] First, tasks with an execution cost score higher than 0.6 (i.e., a normalized cost estimate lower than 0.4) are identified and marked as "high-cost tasks." Then, a negative decay is applied to the priority score of each high-cost task:

[0104] Where μ is the decay step size coefficient (0.2 in this embodiment). This mechanism ensures that when the system is busy, the execution order of resource-intensive tasks is appropriately postponed, thereby prioritizing lightweight tasks and improving overall throughput.

[0105] If the same task triggers both positive increment and negative decay simultaneously, the positive increment is applied first, followed by the negative decay. The adjusted score is used as the final priority score for subsequent ranking.

[0106] S303. Generate an executable task execution pipeline based on the final priority score and the directed acyclic graph of dependencies.

[0107] Sort all atomic query tasks from highest to lowest according to their final priority scores to obtain a candidate task sequence.

[0108] The candidate task sequence only reflects priority, but does not consider dependencies between tasks. The system uses a directed acyclic graph of dependencies as a constraint to perform topological rearrangement of the candidate sequence, ensuring that all predecessor tasks of each task have appeared before it.

[0109] Scan the rearranged task sequence to identify whether there is a dependency relationship between adjacent tasks. If there is no dependency relationship and the priority score difference is less than a preset threshold (0.1 in this embodiment), then mark it as a "parallel execution group" and merge it into a parallel scheduling unit.

[0110] Generate specific execution strategies for each group of parallel tasks: If all tasks within a parallel group are data source scanning types (such as filtering and projection), the system merges them into a single multi-condition composite query, utilizing the parallel scanning capabilities of the database optimizer. If the tasks within a parallel group involve different tables or different computational logic, the system generates two independent subqueries, submits them to the database simultaneously through an asynchronous thread pool, and merges the results at the application layer. If there is a possibility of reusing intermediate results within a parallel task group, the system will prioritize using temporary tables or common table expressions (CTEs) for result caching.

[0111] In one embodiment of the present invention, based on step S4, the following will provide a possible embodiment and describe its specific implementation in a non-limiting manner.

[0112] Traditional NL2SQL methods typically concatenate user queries and database schema information into a large language model, requiring the model to directly output a complete SQL statement. When faced with complex requests involving multiple table joins, nested subqueries, and multiple operation steps, this method is prone to losing logical constraints between tasks, resulting in SQL statements with issues such as misaligned conditions, incorrect aggregation order, and disorganized subquery nesting levels.

[0113] S401. This step proposes a hierarchical prompt word construction strategy, which explicitly injects the structured information of the task execution pipeline into the prompt words, guiding the large language model to generate SQL fragments or final SQL statements step by step according to task priority and dependency.

[0114] Pre-defined three-level prompt structure: System Role Layer: Fixed instructions define the behavioral boundaries and output specifications of the large language model. For example: "You are a professional SQL engineer and must generate SQL statements strictly according to task priority. Prioritize high-priority tasks and ensure correct dependencies. Output should only contain SQL code, requiring no additional explanation." Task Context Layer: Dynamically generated, containing a description of the task pipeline corresponding to the current request. This layer presents the list of atomic tasks, priority order, dependencies, and parallel group information in structured natural language.

[0115] Database schema layer: Dynamic injection, containing only table structure information relevant to the current task pipeline, avoiding interference from redundant information. The system extracts the relevant table structure from the complete metadata based on the field names and table names involved in the task, including table names, field names, field types, primary and foreign key relationships, index information, etc.

[0116] User request layer: Preserves the original user request text as a reference for semantic alignment.

[0117] Input the aforementioned hierarchical prompts into a large language model (such as GPT-4, Tongyi Qianwen, etc.), and the model will output the corresponding SQL statement. Since the task priority and execution order are clearly defined in the prompts, the SQL generated by the model naturally conforms to logical constraints and requires no additional validation.

[0118] Lightweight post-processing is performed on the generated SQL: comments are removed, keyword case is standardized, and execution timeout control statements are added. For scenarios requiring explicit parallel execution (such as task group G1 involving different tables), the system will split it into multiple SQL statements for separate execution. In this case, since filtering and grouping can be combined into the same query, a single SQL statement is generated.

[0119] S402. For complex queries, this step adopts a progressive execution strategy: based on the task pipeline topology, the query is divided into multiple execution stages, and intermediate results are passed between stages through temporary tables or CTEs; parallel tasks can be merged or split into independent SQL, depending on the task to be executed in stages, and each stage of SQL is idempotent.

[0120] Intermediate result caching employs a multi-level strategy: session-level temporary tables, application-level persistent caches, and in-memory result set caches, to avoid redundant scanning and computation.

[0121] Error backtracking and dynamic rescheduling mechanism: When a subtask fails, trace along the dependency chain and block the subsequent task; downgrade the priority of the failed task, remove it from the current pipeline along with the blocked task, reconstruct it and retry it with a reduced priority; if consecutive failures reach a threshold, mark it as unexecutable and return an error message.

[0122] S403. Query Result Preprocessing and Key Indicator Extraction The system identifies and integrates the data types of query results: adds units and simplifies large numbers for numeric types (including currency and percentage); counts frequency, extracts summaries, or retains the original text for text types (enumeration, long text, and names); formats time types uniformly and normalizes granularity; converts Boolean types to "yes / no"; and marks null values ​​as "no data available".

[0123] Key metrics are extracted based on task type and user intent: global extreme values, central tendency, distribution characteristics, trend changes, and ranking results. Template matching and semantic role mapping are employed; for example, aggregation tasks extract sums, and ranking tasks extract the Top N entities and their values.

[0124] Anomaly detection integrates statistical thresholds (mean ± 3 standard deviations), business rules, null and zero value detection, and mutation analysis to mark abnormal data and assign a confidence level (high / medium / low) for subsequent careful interpretation.

[0125] S404. Semantic Enrichment Processing Transform the preprocessed data into natural language elements rich in semantic relationships: Comparison relationship annotation: Automatically identify same-year comparison (A is X times that of B), time-series comparison (X% increase compared to last month), target comparison (completion rate X%), and ranking comparison (ranked Xth), and generate explicit annotations based on field semantics and numerical calculations.

[0126] Time context supplement: Add relative descriptions (today, this month, this year, last year), normalize granularity, describe continuous intervals (last X days, Xth quarter), and mark holidays or periodic nodes.

[0127] Numerical semantic transformation: large number simplification (152,000), ratio expression (38.3%), ordinal expression (ranked 1st), range expression (10,000 to 20,000 yuan), fuzzy modification (approximately, nearly, more than).

[0128] The final output is a semantically enhanced structured data object, which includes: the original result set (simplified), column-level semantic annotations (data type, unit, credibility), row-level semantic annotations (anomalies, comparisons, rankings), a global set of key indicators, and a time context mapping table.

[0129] In one embodiment of the present invention, based on step S5, a possible embodiment will be given below, and its specific implementation will be described in a non-limiting manner.

[0130] S501: Intent Type Recognition and Narrative Template Matching First, the intent classification result of the user request is obtained from the dialogue context (derived from the query intent subtype output by the three-level discrimination mechanism). If it cannot be obtained directly, a second inference is made based on the characteristics of the query statement: if it contains GROUP BY and aggregate functions, it is judged as "statistical analysis"; if it contains detailed fields and no aggregation, it is judged as "detailed query"; if it contains comparison operators or multi-table comparison, it is judged as "comparative analysis"; if it contains anomaly detection or trend fluctuation, it is judged as "exploration and discovery".

[0131] The system has a pre-built library of narrative structure templates: Statistical Analysis: General-Specific Structure (first overall indicators, then dimensional decomposition); Detailed Query: Time / Logical Order Structure (arranged by occurrence sequence or importance); Comparative Analysis: Comparative Structure (presenting differences and similarities in parallel); Exploration and Discovery: Problem-Evidence Structure (first presenting the conclusion, then citing data to support it).

[0132] S502: Dynamic Construction of Three-Level Semantic Hierarchy The system generates three levels of information granularity through a dynamic hierarchical construction algorithm: Core Summary Layer: This layer selects no more than three of the most representative conclusions from the set of key indicators. For example, "In 2023, the sales department had the highest total salary (152,000), accounting for 38% of the entire company." An information entropy ranking algorithm is used to select the indicator with the greatest information gain.

[0133] Detailed analysis layer: The result set is grouped and summarized according to the dimensions involved in the user request (department, time, product category, etc.). For example, "Salary ranking of each department: Sales Department 152,000, R&D Department 98,000, Marketing Department 80,000..." The system automatically identifies the dimension fields and measure fields, generating structured lists or short sentence clusters.

[0134] Raw data reference layer: To prevent information overload, only supporting details are selectively retained. Filtering rules: ① Records directly related to the core summary; ② Outlier records; ③ Detail of user's historical preferences (e.g., habitually viewing the Top 5). This layer is presented in the form of concise tables or key fields.

[0135] S503: Template Filling and Natural Language Polishing The three levels of content are mapped to the corresponding slots in the selected template. The template uses a slot-connector separation design.

[0136] After completion, the prompts undergo coherence validation: detecting duplicate references, completing omitted subjects, and standardizing tense and unit expressions. The final structured prompts can be directly input into a general-purpose model to drive the generation of natural language answers that conform to data insight logic.

[0137] In some embodiments, the SQL query-based intelligent question-answering system may include multiple functional modules composed of computer program segments. The computer programs for each program segment in the SQL query-based intelligent question-answering system may be stored in the memory of a computer device and executed by at least one processor to perform (see details). Figure 1 (Description) Intelligent question answering functionality based on SQL queries.

[0138] In this embodiment, the SQL query-based intelligent question-answering system can be divided into multiple functional modules according to the functions it performs, such as... Figure 4 As shown. The module referred to in this invention is a series of computer program segments that can be executed by at least one processor and perform a fixed function, and is stored in memory. In this embodiment, the functions of each module will be described in detail in subsequent embodiments.

[0139] The intent determination module is used to receive user requests and classify the intent of the user requests through a three-level discrimination mechanism to determine whether to execute a database query. The task construction module is used to decompose the user request into multiple atomic query tasks in response to the execution of a database query, and to identify the dependencies between the atomic query tasks. The task sorting module is used to prioritize the atomic query tasks and generate a task execution pipeline based on the sorting results and dependencies. The query processing module is used to generate and execute corresponding SQL query statements based on the task execution pipeline, obtain query results, and perform data preprocessing and semantic enrichment on the query results. The answer generation module is used to construct structured prompts from the processed query results using a semantic hierarchical organization strategy, input the structured prompts into a general large model, generate natural language answers, and output them.

[0140] Figure 5 The SQL query-based intelligent question-answering method provided in this application embodiment can be applied to a device. The device 500 may include a processor 510, a memory 520, and a communication unit 530. These components communicate via one or more buses. Those skilled in the art will understand that the server structure shown in the figures does not constitute a limitation of the invention; it can be a bus topology, a star topology, and may include more or fewer components than shown, or combine certain components, or have different component arrangements.

[0141] The present invention also provides a computer storage medium, wherein the computer storage medium may store a program, which, when executed, may include some or all of the steps provided in the embodiments of the present invention. The storage medium may be a magnetic disk, an optical disk, read-only memory (ROM), or random access memory (RAM), etc.

[0142] Although the present invention has been described in detail with reference to the accompanying drawings and preferred embodiments, the present invention is not limited thereto. Various equivalent modifications or substitutions can be made to the embodiments of the present invention by those skilled in the art without departing from the spirit and essence of the invention, and such modifications or substitutions should all be within the scope of the present invention. Any variations or substitutions that can be easily conceived by those skilled in the art within the technical scope disclosed in the present invention should also be covered within the protection scope of the present invention.

Claims

1. An intelligent question-answering method based on SQL queries, characterized in that, include: Upon receiving a user request, the user request is classified into intents using a three-level discrimination mechanism to determine whether to execute a database query. In response to executing a database query, the user request is decomposed into multiple atomic query tasks, and the dependencies between the atomic query tasks are identified. The atomic query tasks are prioritized, and a task execution pipeline is generated based on the prioritization results and dependencies. Based on the task execution pipeline, the corresponding SQL query statement is generated and executed to obtain the query result, and the query result is subjected to data preprocessing and semantic enrichment processing. A semantic hierarchical organization strategy is adopted to construct structured prompts from the processed query results. These structured prompts are then input into a general large model to generate and output natural language answers.

2. The method according to claim 1, wherein the user request is classified into intents using a three-level discrimination mechanism to determine whether the user request is a database query intent, comprising: In the first-level discrimination stage, the user request is matched with keywords or regular expressions based on a preset non-query intent rule base; If any rule in the non-query intent rule base is matched, it is directly determined to be a non-database query intent, and the intent classification process is terminated. In the second-level discrimination stage, in response to the user request not being determined as a non-database query intent in the first level, the syntactic features, semantic vector similarity features, and domain entity link features of the user request are extracted, and the extracted features are input into the query intent classification model to output the query probability score that the user request belongs to the database query intent. In the third-level discrimination stage, a preset benchmark threshold is set, and the query probability score is compared with the benchmark threshold; when the query probability score is greater than or equal to the benchmark threshold, it is determined to be a database query intent. When the query probability score is less than the baseline threshold, it is determined to be a non-database query intent.

3. The method according to claim 2, characterized in that, The method also includes a threshold adaptive adjustment mechanism: When there is a previous database query request in the previous context of this dialogue round, and the current user request contains an abbreviated instruction, the value of the baseline threshold will be temporarily reduced to adapt to the information sparsity of the current request. In response to a user's correction operation on the query result, identify misjudgment cases caused by incorrect intent classification from the correction operation, and calculate the misjudgment rate according to a preset period. When the false positive rate is higher than a first preset threshold, the benchmark threshold is increased; when the false positive rate is lower than a second preset threshold, the benchmark threshold is decreased. The baseline threshold is set to its initial value when there are no temporary adjustments.

4. The method according to claim 1, characterized in that, In response to executing a database query, the user request is decomposed into multiple atomic query tasks, and the dependencies between the atomic query tasks are identified, including: The user request is subjected to dependency parsing and semantic role labeling to generate a syntactic dependency tree with words as nodes and dependency relations as edges. Core predicates, argument structures and modifiers are extracted from the syntactic dependency tree. Based on the syntactic dependency tree and semantic role labeling results, each predicate-argument combination or modification-qualifying structure with independent query semantics in the user request is identified as an operation unit; a unique identifier is assigned to each operation unit, and the one or more word nodes covered by the operation unit in the syntactic dependency tree and their position information are recorded; Each operation unit is mapped to an atomic query task. The mapping rule is as follows: based on the core predicate and argument type of the operation unit, a preset task type template is matched. The task type template includes one or more of the following: conditional filtering task, aggregation calculation task, sorting operation task, grouping aggregation task, multi-table association task, and limited output task. The mapped atomic query task is encapsulated into an independent task object. Each task object contains a task type, a set of related word nodes, and parameter information extracted from the operation unit. Traverse the syntactic dependency tree and identify the explicit associations between the word node sets corresponding to the atomic query tasks based on the following syntactic dependency features: dependency edge type, conjunctions, punctuation marks, and order adverbs. Based on the explicit associations, generate parallel relationships, sequential dependencies, or nested inclusion relationships between the atomic query tasks, and label the pre-task set and post-task set of each task accordingly. For atomic query tasks that do not establish associations through explicit dependency identification, implicit dependencies are identified based on data dependencies, semantic dependencies, and domain knowledge; the identified implicit dependencies are then added to the pre-task set and post-task set of each task. Using atomic query tasks as nodes and the dependencies defined in the pre-task set and post-task set as directed edges, an initial directed graph is constructed; the initial directed graph is topologically sorted and verified, and if a circular dependency is detected, a conflict resolution strategy is triggered until a directed acyclic graph is generated. The final verified directed acyclic graph is used as the dependency representation for the atomic query task.

5. The method according to claim 1, characterized in that, The atomic query tasks are prioritized, and a task execution pipeline is generated based on the prioritization results and dependencies, including: Priority scores for each task are calculated by weighting and summing semantic tightness, dependency, execution cost, and historical weights. In response to user emphasis, apply a positive increment to the priority score of the emphasized task; in response to database load exceeding the threshold, apply a negative decay to the priority score of high-cost tasks. Sort tasks in descending order of priority and perform topology rearrangement based on the directed acyclic graph of dependencies; mark adjacent tasks with no dependencies and similar priorities as parallel groups to generate a task execution pipeline that includes both serial order and parallel strategies.

6. The method according to claim 1, characterized in that, Based on the task execution pipeline, corresponding SQL query statements are generated and executed to obtain query results. The query results are then subjected to data preprocessing and semantic enrichment, including: The task execution pipeline, database table structure, and user requests are integrated into hierarchical prompt words, which are then input into a large language model to generate SQL query statements that conform to task priorities. For complex queries, a progressive execution strategy is adopted, which decomposes them into multiple subqueries and executes them step by step; intermediate results of high-priority tasks are cached; in response to the failure of a subtask, its priority is automatically reduced and the pipeline is rescheduled. Identify the data type of the query results and adopt the corresponding integration strategy; extract key indicators including maximum value, minimum value, and trend characteristics; detect and mark abnormal data points; Comparison relationships between labeled data; add relative time context descriptions to time series data.

7. The method according to claim 1, characterized in that, The processed query results are organized into structured suggestion terms using a semantic hierarchical organization strategy, including: Identify the intent type of the user request and match the data organization logic corresponding to the intent type from a preset narrative structure template library; the intent type includes statistical analysis, detailed query, comparative analysis, and exploration and discovery; the narrative structure template includes general-to-specific structure, time or logical order structure, comparison structure, and question-evidence structure. A three-level semantic hierarchy is generated through a dynamic hierarchical construction algorithm. The three-level semantic hierarchy includes: Core summary layer: extracting no more than a preset number of key conclusions or core indicators from the query results; Detailed analysis layer: grouping and summarizing the query results according to one or more data dimensions to generate structured analysis content; Original data citation layer: selectively retaining representative or supporting detailed data entries from the query results. The content of the three semantic levels is filled into the corresponding variable slots of the selected narrative structure template, and the selection of the connecting word library is adjusted according to the preset style adjustment parameters to generate structured prompt words with natural language coherence.

8. An intelligent question-answering system based on SQL queries, characterized in that, include: The intent determination module is used to receive user requests and classify the intent of the user requests through a three-level discrimination mechanism to determine whether to execute a database query. The task construction module is used to decompose the user request into multiple atomic query tasks in response to the execution of a database query, and to identify the dependencies between the atomic query tasks. The task sorting module is used to prioritize the atomic query tasks and generate a task execution pipeline based on the sorting results and dependencies. The query processing module is used to generate and execute corresponding SQL query statements based on the task execution pipeline, obtain query results, and perform data preprocessing and semantic enrichment on the query results. The answer generation module is used to construct structured prompts from the processed query results using a semantic hierarchical organization strategy, input the structured prompts into a general large model, generate natural language answers, and output them.

9. An intelligent question-answering device based on SQL queries, characterized in that, include: Memory is used to store intelligent question-answering programs based on SQL queries; A processor, configured to implement the steps of the SQL query-based intelligent question-answering method as described in any one of claims 1-7 when executing the SQL query-based intelligent question-answering program.

10. A computer-readable storage medium storing a computer program, characterized in that, The readable storage medium stores an intelligent question-answering program based on SQL queries, which, when executed by a processor, implements the steps of the intelligent question-answering method based on SQL queries as described in any one of claims 1-7.