node+express编写后台模糊查询命令遇到的坑

废话就不多说了,直接上问题,以搜索文章为例:

controllers里的请求语句:

async function search(req, res) {
  const { title, author } = req.query;
  if (!title && !author) {
    return sendMissParamResponse(res, true)
  }
  const data = await Article.searchArticle(
    title || '',
    author || ''
  );
}

models里的查询语句:

const searchArticle = (title, author) => sequelize.query(
  ArticleSQL.search,
  {
    replacements: [
      `%${title}%`,
      `%${author}%`
    ],
    type: sequelize.QueryTypes.SELECT
  }
);

注意:replacements中的`%${ title }%`就是模糊查询的SQL语法,大家都知道这是es6字符串拼接的写法,${ title }表示是你从前端传过来的参数,意思就是搜索 title = xxxx的文章,下面的author相同,不再赘述。

sql里的SQL语句:

  search: `
    SELECT DISTINCT
      article.id,
      article.title,
      account_info.avatar img,
      DATE_FORMAT(article.create_time,"%Y-%m-%d %h:%i:%s") time,
      account_info.uuid,
      account_info.name userName
    FROM
      article, account_info, type
    WHERE
      article.user_id = account_info.uuid AND
      article.status = 1 AND
      (article.title LIKE ? OR
      account_info.name LIKE ?)
    ORDER BY
      article.create_time desc
  `,

主要是在WHERE里的语句比较重要,特别是这一句:(article.title LIKE ? OR account_info.name LIKE ?)
之前我们具体查询的时候用的是 ' = ' ,但是模糊查询用的是 ' LIKE ' 。

但是你会发现,不管你在搜索栏里输入啥,返回的结果都是一样的!很是无语,怎么查找问题(浏览器没报错,所以不属于错误的范畴)呢?或者你将上述的SQL语句输入到SQLyog工具里去试,发现出现的数据是非正常的,不是你预期的那样。

问题解决:

在前端进行传值的时候,应先进行处理,或者在后台controllers里处理也是一样的,怎么处理?

如果输入框中title有值,而author为空,这个时候我们很容易处理成空字符串,但是我们似乎忘记了一件事,就是在创建表的时候,在创建字段的时,字段默认的值类型为NULL,也就是说,在SQL查询语句中查询数据时,最好将空的数据变为当初设置的默认类型NULL。

以代码为例:

async function search(req, res) {
  const { title, author } = req.query;
  if (!title && !author) {
    return sendMissParamResponse(res, true)
  }
  const data = await Article.searchArticle(
    title || null,
    author || null
  );
}

也就是在处理title和author为空的时候,数据类型应为null而不是字符串。

你可能感兴趣的:(react,express,node,SQL)