> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/build/database/text2sql.md).

# Text to SQL 功能

本篇將介紹如何在 MaiAgent 系統中使用 Text to SQL 功能，協助您使用日常對話輕鬆查詢資料庫內資訊

## **什麼是 Text to SQL？** <a href="#what-is-text-to-sql" id="what-is-text-to-sql"></a>

**Text to SQL**（又稱為 Text2SQL），是一個能將**自然語言問題**（人類的日常用語）自動轉換成 **SQL 資料庫查詢語句**的智慧工具。簡單來說，就是讓 Agent 能夠「<mark style="color:blue;">聽懂人話</mark>」並直接操作資料庫。

{% hint style="info" %}
欲了解更多 Text2SQL 內容，請見：[技術人員手冊—Text to SQL](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql)
{% endhint %}

想像你是便利商店老闆：

**傳統方式：**

* 你：「幫我查一下昨天賣了多少瓶可樂」
* 員工：「老闆，你要教我怎麼用收銀系統查詢...」
* 你：「點這裡、選那裡、輸入條件...」

需要手把手教學，較耗費時間。

**有了 Text2SQL：**

* 你：「幫我查一下昨天賣了多少瓶可樂」
* AI 員工：「好的！」💫 *(自動產出查詢方法並調用資料庫)* → 「昨天賣了87瓶可樂」✅

### **Text to SQL 的核心功能** <a href="#text-to-sql-core-features" id="text-to-sql-core-features"></a>

```
自然語言問題 → AI 理解分析 → SQL 查詢語句 → 執行查詢 → 回傳結果
```

當你問 Agent「找出昨天賣最好的飲料」，Agent 會先分析你的問題，知道你要找「飲料」而且是「昨天」賣「最好」的，然後生成 SQL 語法去資料庫查詢，最後把結果「可樂」告訴你。

## **Text to SQL 可以協助 AI 做到的事情** <a href="#what-text-to-sql-can-do" id="what-text-to-sql-can-do"></a>

### **具體應用場景** <a href="#use-cases" id="use-cases"></a>

#### **🏥 醫療診所** <a href="#medical-clinic" id="medical-clinic"></a>

```
醫生問：「找出今天預約的糖尿病患者」
AI回答：「今天共有5位糖尿病患者預約：
- 王先生 10:00 回診
- 李太太 14:30 追蹤檢查
- 陳小姐 16:00 血糖監測」
```

#### **🏫 學校管理** <a href="#school-management" id="school-management"></a>

```
老師問：「這次考試有多少學生不及格？」
AI回答：「本次數學考試：
- 總人數：45人
- 不及格：8人（17.8%）
- 需要補考的學生名單已整理完成」
```

#### **🏪 零售連鎖店** <a href="#retail-chain" id="retail-chain"></a>

```
店經理問：「比較三間分店的月營收」
AI回答：「11月各分店營收比較：
- 台北店：$1,200,000 (↑15%)
- 台中店：$950,000 (↑8%)  
- 高雄店：$800,000 (↓3%)」
```

### **Text to SQL 的優勢** <a href="#text-to-sql-advantages" id="text-to-sql-advantages"></a>

#### **⚡ 效率提升** <a href="#efficiency-improvement" id="efficiency-improvement"></a>

* **傳統方式**：需要 SQL 專家寫查詢 → 30分鐘
* **Text2SQL**：自然語言提問 → 3秒鐘

#### **🎯 降低門檻** <a href="#lower-barrier" id="lower-barrier"></a>

* **不需要**學習複雜的 SQL 語法
* **不需要**記住資料庫結構
* **任何人**都能查詢資料

#### **📱 即時互動** <a href="#real-time-interaction" id="real-time-interaction"></a>

* 問了就有答案
* 支援後續追問
* 動態調整查詢條件

## 如何在 MaiAgent 中使用 Text to SQL 功能 <a href="#how-to-use-text-to-sql-in-maiagent" id="how-to-use-text-to-sql-in-maiagent"></a>

資料庫在左側選單的「<mark style="color:blue;">AI 功能</mark>」→「<mark style="color:blue;">資料庫</mark>」集中建立，一個資料庫可以給多個 Agent 使用，一個 Agent 也可以關聯多個資料庫。設定分成三步：

### 1. 建立並啟用資料庫 <a href="#enter-database-url" id="enter-database-url"></a>

在「<mark style="color:blue;">資料庫</mark>」頁點選「<mark style="color:blue;">新增資料庫</mark>」，選擇資料庫類型：

* **MaiAgent 資料庫**：沒有自建資料庫時使用，上傳 Excel、CSV 或 JSON 檔案，系統自動建立資料表，不需要連線字串。見 [MaiAgent 資料庫進行 Text to SQL](/build/database/text-to-sql-maiagent.md)。
* **外部資料庫**：連接既有的 PostgreSQL、MySQL、SQL Server、Oracle 或 SynxDB，需要填寫連線字串，並先確認資料庫允許 MaiAgent 連入。

新建立的資料庫預設為停用，請開啟「<mark style="color:blue;">啟用資料庫</mark>」後，Agent 才會查詢它。完整步驟、各資料庫的連線字串格式與網路檢查清單，見 [建立與設定資料庫](/build/database/create-database.md)。

### 2. 將 Agent 切換為 Agent 模式 <a href="#switch-to-agent-mode" id="switch-to-agent-mode"></a>

在 Agent 的 <mark style="color:blue;">設定</mark> 點選左側導覽的「<mark style="color:blue;">回答模式設定</mark>」，選擇 <mark style="color:blue;">Agent 模式</mark>。

{% hint style="warning" %}
Text to SQL 只在 Agent 模式下可用。其他回答模式的 Agent，左側導覽的「<mark style="color:blue;">資料庫設定</mark>」會鎖定，無法選擇資料庫。各回答模式的說明見 [建立 Agent](/build/agent/setup.md#select-answer-mode-to-build-prompt)。
{% endhint %}

### 3. 關聯資料庫與 Agent <a href="#link-database-to-agent" id="link-database-to-agent"></a>

以下兩種方式擇一：

* 在 Agent 的 <mark style="color:blue;">設定</mark> 點選左側導覽的「<mark style="color:blue;">資料庫設定</mark>」，按「<mark style="color:blue;">選擇資料庫</mark>」勾選要查詢的資料庫，再點選儲存。
* 在資料庫設定頁的「<mark style="color:blue;">關聯 AI 助理</mark>」頁籤，把 Agent 移到右側後儲存，見 [關聯 Agent 與群組權限](/build/database/link-chatbots-groups.md)。

設定完成後，就能在 Agent 的對話中用自然語言查詢資料，例如「上個月哪個產品銷售最多？」。

## **常見問題排除** <a href="#troubleshooting" id="troubleshooting"></a>

* **連線失敗**：檢查連線字串格式、帳號密碼，以及防火牆與白名單是否已開放，見 [建立與設定資料庫：網路前置](/build/database/create-database.md#network-prerequisites)。
* **Agent 沒有查資料庫**：確認回答模式是 Agent 模式、資料庫已啟用，並已關聯到這個 Agent。
* **Agent 只查資料庫、回覆說沒有知識庫檢索工具**：Agent 模式下知識庫檢索也是一組工具（`retrieve_text_nodes` 等），開啟 <mark style="color:blue;">啟用工具搜尋功能</mark> 時，這些工具和 Text to SQL 一樣要先被搜尋到才能呼叫，模型偶爾會跳過搜尋直接回答「沒有工具」。請在角色指令寫明「回答前先用 retrieve\_text\_nodes 查詢知識庫」，或關閉工具搜尋讓所有工具直接可用，見 [為 Agent 配置工具](/build/tools/configure_tools.md)；兩種模式的檢索差異見[技術人員手冊 - 對話模式與 Agent 模式怎麼查知識庫](https://docs.maiagent.ai/tech/quickstart/rag#chat-vs-agent-retrieval)。
* **想限制某些使用者只能查部分資料**：[查詢元資料](/org/querymetadata.md#scope-and-limits)只限制知識庫檢索，不會套用到 Text to SQL；資料庫的範圍只能用啟用／關聯 Agent、<mark style="color:blue;">指定資料表</mark> 與角色權限控制，無法逐次請求限制。需要依使用者分流時，請為不同身分建立不同的 Agent 與資料庫連線（或唯讀帳號）。
* **查詢錯誤**：確認表名和欄位名稱正確，並為資料表與欄位補上描述，見 [編輯欄位描述](/build/database/create-database.md#edit-column-description)。
* **權限不足**：檢查資料庫帳號是否有這些資料表的讀取權限。
* **回應慢**：檢查查詢複雜度，考慮加入索引，或用「<mark style="color:blue;">指定資料表</mark>」縮小查詢範圍。

規格面的說明（唯讀保護、網路需求、大型 schema 的處理與查詢結果上限）見 [技術人員手冊 - Text to SQL](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql)。

***

Text2SQL 讓 Agent 變成資料庫專家，任何人都能用自然語言快速獲取業務洞察，大幅提升數據驅動決策的效率！


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/build/database/text2sql.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
