MySQL - 是否可以对表中的所有列使用 LIKE?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18415820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:38:32  来源:igfitidea点击:

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

mysqlwheresql-like

提问by user2566387

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:

我正在尝试制作一个简单的搜索栏,用于在我的数据库中搜索某些单词。可以在不使用 WHERE 的情况下使用 LIKE 属性吗?我希望它搜索关键字的所有列,而不仅仅是一列。目前我有这个:

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?

并且都没有工作。这是可能的还是有另一种方法来解决它?

采纳答案by Dave

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

您可能还想查看 MATCH() 函数,例如:

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.

您还可以获取相关性分数并添加 FULLTEXT 键以加快查询速度。

回答by JJJ

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

回答by esdiweb

There IS a shortcut ! ;)

有捷径!;)

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

回答by Harsha

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