You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js 结合 MySQL 实现部分匹配查询的方法求助

解决Node.js中SQL Server模糊查询无结果的问题

问题根源

你写的'%@nameContent%'会被SQL Server当作字面量字符串处理,它不会把@nameContent解析为参数,而是直接查找包含@nameContent文本的内容,自然匹配不到任何结果。

两种正确的解决方案

方案1:在代码中给参数值添加通配符

保持查询语句使用纯参数,在Node.js代码里给用户输入的关键词前后加上%,再传入参数:

  1. 定义查询语句:
export const querys = {
  searchContentByName: "SELECT TOP 10 * FROM content where nameContent like @nameContent"
};

(加上TOP 10满足你返回10部电影的需求)

  1. 执行查询时处理参数:
// 假设使用mssql库,用户输入的关键词为searchKeyword
const searchKeyword = "fight";
const request = new sql.Request();
// 给关键词前后拼接%
request.input('nameContent', sql.NVarChar, `%${searchKeyword}%`);
const result = await request.query(querys.searchContentByName);

方案2:在SQL语句中用CONCAT拼接通配符

直接在SQL里用CONCAT函数把%和参数拼接,无需在代码里处理参数:

定义查询语句:

export const querys = {
  searchContentByName: "SELECT TOP 10 * FROM content where nameContent like CONCAT('%', @nameContent, '%')"
};

执行时直接传入原始关键词即可,SQL会自动拼接通配符。

额外注意事项

  • 避免SQL注入:绝对不要直接把用户输入拼接到SQL语句里(比如SELECT * FROM content where nameContent like '%${searchKeyword}%'),必须使用参数化查询。
  • 不区分大小写搜索:如果需要忽略大小写匹配,可以用LOWER/UPPER函数统一转换:
SELECT TOP 10 * FROM content where LOWER(nameContent) like CONCAT('%', LOWER(@nameContent), '%')

或者修改数据库表的排序规则为不区分大小写(比如SQL_Latin1_General_CP1_CI_AS)。

内容的提问来源于stack exchange,提问作者mara345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:20:44