【问题标题】:MySql Store Procedure Search LikeMySql 存储过程搜索喜欢
【发布时间】:2020-11-05 09:19:40
【问题描述】:

我有一个名为“查询”的参数搜索字段,此参数将搜索不同的列以进行匹配。它可以工作,但查询必须完全匹配才能获得返回。我曾尝试使用 '%' 但我认为我没有正确使用它。我正在尝试进行更通用的搜索。

CREATE DEFINER=`root`@`localhost` PROCEDURE `client_search_reps`(IN offset INT, IN row_count INT, IN query varchar(100))
BEGIN

    SELECT
            U.Id,
            U.RoleId,
            UP.FirstName,
            UP.LastName,
            UP.FileUrl,
            L.City,
            L.Zip,
            CP.Name,
            CP.Url,
            CP.Phone,
            CP.Email,
            P.ProductOne,
            P.ProductTwo,
            P.ProductThree,
            P.ProductFour,


        FROM user_profiles AS UP
        LEFT JOIN users AS U ON U.Id = UP.UserId
        LEFT JOIN location AS L ON  L.UserProfileId = UP.UserId
        LEFT JOIN company_profile AS CP ON CP.UserId = UP.UserId
        LEFT JOIN products AS P ON P.UserId = U.Id
        
        WHERE UP.FirstName LIKE query || UP.LastName LIKE query || CP.Name LIKE query 
        || CP.Phone LIKE query || CP.Email LIKE query
        
        LIMIT offset, row_count;
            
END

下面是我的 React.Js 代码,以防万一它有助于理解我的问题。



searchAccount = (query) => {
    profileServices
      .searchAccounts(0, query)
      .then(this.searchSuccess)
      .catch(this.searchError);
  };

  searchSuccess = (data) => {
    let accounts = data.item.pagedItems;
    this.setState({
      mappedProfiles: accounts.map(this.mapSearch),
      currentItems: data.item.totalCount,
    });
  };

  searchError = (data) => {
    swal({
      title: "Search is Broad",
      text: "Search by: Company Name, Phone, or Email",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    });
  };

  onSearch = (e) => {
    let value = e.target.value;
    this.setState((prevState) => {
      return {
        ...prevState,
        query: value,
      };
    });
  };

  clearSearch = () => {
    this.setState((prevState) => {
      return {
        ...prevState,
        query: "",
      };
    });
    // this.getProfiles(0);
  };

  search = () => {
    if (this.state.query.length > 0 ? this.searchAccount(this.state.query) : 0);
    this.setState({
      searchModal: true,
    });
  };

【问题讨论】:

    标签: mysql stored-procedures mysql-workbench


    【解决方案1】:

    您可以将 SQL 的通配符添加到query

    CREATE PROCEDURE client_search_reps(
    offset INT, 
    row_count INT, 
    query varchar(100)
    )
    BEGIN
    
    SET query = CONCAT('%', query, '%');
    ...
    

    顺便说一句,最好使用标准OR 而不是非标准||(|| 在 MySQL 8.0.17 中已弃用,并且根据所有版本中使用的 sql_mode 具有不同的行为)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-16
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多