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

…衆ロ難τιáo~ 提交于 2019-11-30 14:40:24

问题


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 search all columns for the keywords, not just one. Currently I have this:

mysql_query("SELECT * FROM shoutbox WHERE name LIKE '%$search%' ")

Which obviously only searches for names with the search input. I tried both of these:

mysql_query("SELECT * FROM shoutbox LIKE '%$search%' ")
mysql_query("SELECT * FROM shoutbox WHERE * LIKE '%$search%' ")

and neither worked. Is this something that is possible or is there another way to go about it?


回答1:


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.




回答2:


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%' 



回答3:


There IS a shortcut ! ;)

SELECT * FROM shoutbox 
WHERE CONCAT(name, foo, bar, baz) LIKE '%$search%' 



回答4:


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%') 


来源:https://stackoverflow.com/questions/18415820/mysql-is-it-possible-to-use-like-on-all-columns-in-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!