简体   繁体   English

在整个表格中搜索单词-MySQL

[英]search for a word in entire table - MySQL

Currently am using the following code for search for a word in the entire table, 目前,我正在使用以下代码在整个表格中搜索单词,

    Dim searchKey As String = "Sample"
    Dim mysql As String = "SELECT * FROM myTable " & _
                          "WHERE col1 LIKE '%" & searchKey & "%' " & _
                          " OR col2 LIKE '%" & searchKey & "%' " & _
                          " OR col3 LIKE '%" & searchKey & "%' " & _
                          " OR col4 LIKE '%" & searchKey & "%' "

But querying became more difficult when the number of column increases . 但是,当列数增加时,查询变得更加困难。 so can anyone suggest me some alternative method for do the same. 所以任何人都可以建议我一些替代方法来做同样的事情。

use a loop to build your String programmatically .in this example you only need to add your columns to array. 使用循环以编程方式构建String。在此示例中,您只需要将列添加到数组即可。

Dim searchKey As String = "Sample"
Dim array() As String = {"col1", "col2", "col3", "col4"}
Dim b As Boolean = True

Dim mysql As String = "SELECT * FROM myTable WHERE "

For Each str As String In array
    If b Then
        mysql = mysql & str + " LIKE '%" & searchKey & "%'"
    Else
        mysql = mysql & " OR " & str & " LIKE '%" & searchKey & "%'"
    End If
    b = False

Next

Debug.WriteLine(mysql)

output>> 输出>>

SELECT * FROM myTable WHERE col1 LIKE '%Sample%' OR col2 LIKE '%Sample%' OR col3 LIKE '%Sample%' OR col4 LIKE '%Sample%'

You can also take help of the fulltext search provided by MySQL. 您还可以利用MySQL提供的全文搜索。 This link provides details on fulltext search, http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html 该链接提供了全文搜索的详细信息, http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html

您可以执行以下操作:如果表结构发生更改,则需要从查询中添加/删除列。

SELECT * FROM myTable WHERE Concat(col1, '',col2, '', coln) LIKE '%searchKey%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM