Mysql query search a string in all columns of a table

后端 未结 4 1353
一向
一向 2021-01-27 11:43

I wonder how I can mount a SQL as portable as possible to query for all columns of a table for a specific phrase, like:

Table

ID | Name          


        
4条回答
  •  天涯浪人
    2021-01-27 12:27

    It's doable, although I strongly suggest you look into full-text search for efficiency;

    To avoid looking for all patterns in all fields one by one, you can just concat and search in that;

    SELECT *
    FROM (SELECT id,CONCAT(name,'|',text,'|',date,'|',author,'|',status) txt
          FROM Table1) a
    WHERE txt LIKE '%augusto%'
      AND txt LIKE '%2010%'
      AND txt LIKE '%text%';
    

    Note that no indexing will help you here, since you're searching in a calculated column. On the other hand, since you're searching with a leading wildcard %searchterm, you won't get much help from indexes even if searching field by field :)

    An SQLfiddle to test with.

提交回复
热议问题