MySQL - Is it possible to use LIKE on all columns in a table?

前端 未结 4 1678
暗喜
暗喜 2020-12-16 13:41

I\'m trying to make a simple search bar that searches through my database for certain words. It is possible to use the LIKE attribute without using WHERE? I want it to sear

相关标签:
4条回答
  • 2020-12-16 13:47

    There's no shortcut. You need to specify each column separately.

    SELECT * FROM shoutbox 
        WHERE name LIKE '%$search%' 
            OR foo LIKE '%$search%' 
            OR bar LIKE '%$search%'  
            OR baz LIKE '%$search%' 
    
    0 讨论(0)
  • 2020-12-16 13:47

    There IS a shortcut ! ;)

    SELECT * FROM shoutbox 
    WHERE CONCAT(name, foo, bar, baz) LIKE '%$search%' 
    
    0 讨论(0)
  • 2020-12-16 13:53

    this will not show duplicate rows anymore.

    SELECT * FROM shoutbox 
    WHERE (name LIKE '%$search%' 
        OR foo LIKE '%$search%' 
        OR bar LIKE '%$search%'  
        OR baz LIKE '%$search%') 
    
    0 讨论(0)
  • 2020-12-16 13:58

    You might want to look at the MATCH() function as well eg:

    SELECT * FROM shoutbox 
    WHERE MATCH(`name`, `foo`, `bar`) AGAINST ('$search')
    

    You can also add boolean mode to this:

    SELECT * FROM shoutbox 
    WHERE MATCH(`name`, `foo`, `bar`) AGAINST ('$search') IN BOOLEAN MODE
    

    You can also get the relevance scores and add FULLTEXT keys to speed up the queries.

    0 讨论(0)
提交回复
热议问题