简体   繁体   English

在 MySQL 数据库的每个表的字段中搜索文本

[英]Search text in fields in every table of a MySQL database

I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:我想在 MySQL 数据库的所有表中搜索给定字符串的所有字段,可能使用如下语法:

SELECT * FROM * WHERE * LIKE '%stuff%'

Is it possible to do something like this?有可能做这样的事情吗?

您可以对数据库(及其数据)执行SQLDump ,然后搜索该文件。

If you have phpMyAdmin installed use its 'Search' feature.如果您安装了 phpMyAdmin,请使用它的“搜索”功能。

  • Select your DB选择您的数据库
  • Be sure you do have a DB selected (ie not a table, otherwise you'll get a completely different search dialog)确保你选择了一个数据库(即不是表,否则你会得到一个完全不同的搜索对话框)
  • Click 'Search' tab单击“搜索”选项卡
  • Choose the search term you want选择您想要的搜索词
  • Choose the tables to search选择要搜索的表

I have used this on up to 250 table/10GB databases (on a fast server) and the response time is nothing short of amazing.我已经在多达 250 个表/10GB 的数据库(在一个快速的服务器上)上使用了它,并且响应时间非常惊人。

You can peek into the information_schema schema.您可以查看information_schema架构。 It has a list of all tables and all fields that are in a table.它具有所有表和表中所有字段的列表。 You can then run queries using the information that you have gotten from this table.然后,您可以使用从该表中获得的信息运行查询。

The tables involved are SCHEMATA, TABLES and COLUMNS.涉及的表是 SCHEMATA、TABLES 和 COLUMNS。 There are foreign keys such that you can build up exactly how the tables are created in a schema.有外键,您可以准确地构建在模式中创建表的方式。

PHP function: PHP函数:

function searchAllDB($search){
    global $mysqli;

    $out = "";

    $sql = "show tables";
    $rs = $mysqli->query($sql);
    if($rs->num_rows > 0){
        while($r = $rs->fetch_array()){
            $table = $r[0];
            $out .= $table.";";
            $sql_search = "select * from ".$table." where ";
            $sql_search_fields = Array();
            $sql2 = "SHOW COLUMNS FROM ".$table;
            $rs2 = $mysqli->query($sql2);
            if($rs2->num_rows > 0){
                while($r2 = $rs2->fetch_array()){
                    $column = $r2[0];
                    $sql_search_fields[] = $column." like('%".$search."%')";
                }
                $rs2->close();
            }
            $sql_search .= implode(" OR ", $sql_search_fields);
            $rs3 = $mysqli->query($sql_search);
            $out .= $rs3->num_rows."\n";
            if($rs3->num_rows > 0){
                $rs3->close();
            }
        }
        $rs->close();
    }

    return $out;
}

You can use this project: http://code.google.com/p/anywhereindb 您可以使用以下项目: http : //code.google.com/p/anywhereindb

This will search all the data in all table. 这将搜索所有表中的所有数据。

If you are avoiding stored procedures like the plague, or are unable to do a mysql_dump due to permissions, or running into other various reasons.如果您正在避免像瘟疫一样的stored procedures ,或者由于权限而无法执行mysql_dump ,或者mysql_dump其他各种原因。

I would suggest a three-step approach like this:我建议采用这样的三步方法:

1) Where this query builds a bunch of queries as a result set. 1) 此查询在哪里构建一堆查询作为结果集。

# =================
# VAR/CHAR SEARCH
# =================
# BE ADVISED USE ANY OF THESE WITH CAUTION
# DON'T RUN ON YOUR PRODUCTION SERVER 
# ** USE AN ALTERNATE BACKUP **

SELECT 
    CONCAT('SELECT * FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME, 
           ' WHERE ', A.COLUMN_NAME, ' LIKE \'%stuff%\';') 
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE 
            A.TABLE_SCHEMA != 'mysql' 
AND     A.TABLE_SCHEMA != 'innodb' 
AND     A.TABLE_SCHEMA != 'performance_schema' 
AND     A.TABLE_SCHEMA != 'information_schema'
AND     
        (
            A.DATA_TYPE LIKE '%text%'
        OR  
            A.DATA_TYPE LIKE '%char%'
        )
;

. .

# =================
# NUMBER SEARCH
# =================
# BE ADVISED USE WITH CAUTION

SELECT 
    CONCAT('SELECT * FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME, 
           ' WHERE ', A.COLUMN_NAME, ' IN (\'%1234567890%\');') 
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE 
            A.TABLE_SCHEMA != 'mysql' 
AND     A.TABLE_SCHEMA != 'innodb' 
AND     A.TABLE_SCHEMA != 'performance_schema' 
AND     A.TABLE_SCHEMA != 'information_schema'
AND     A.DATA_TYPE IN ('bigint','int','smallint','tinyint','decimal','double')
;

. .

# =================
# BLOB SEARCH
# =================
# BE ADVISED THIS IS CAN END HORRIFICALLY IF YOU DONT KNOW WHAT YOU ARE DOING
# YOU SHOULD KNOW IF YOU HAVE FULL TEXT INDEX ON OR NOT
# MISUSE AND YOU COULD CRASH A LARGE SERVER
SELECT 
    CONCAT('SELECT CONVERT(',A.COLUMN_NAME, ' USING utf8) FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME, 
           ' WHERE CONVERT(',A.COLUMN_NAME, ' USING utf8) IN (\'%someText%\');') 
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE 
            A.TABLE_SCHEMA != 'mysql' 
AND     A.TABLE_SCHEMA != 'innodb' 
AND     A.TABLE_SCHEMA != 'performance_schema' 
AND     A.TABLE_SCHEMA != 'information_schema'
AND     A.DATA_TYPE LIKE '%blob%'
;

Results should look like this:结果应如下所示:

将这些结果复制到另一个查询窗口

2) You can then just Right Click and use the Copy Row (tab-separated) 2)然后您可以Right Click并使用Copy Row (tab-separated)

在此处输入图片说明

3) Paste results in a new query window and run to your heart's content. 3) 将结果粘贴到一个新的查询窗口中并运行到您心中的内容。

Detail: I exclude system schema's that you may not usually see in your workbench unless you have the option Show Metadata and Internal Schemas checked.详细信息:我排除了您通常不会在工作台中看到的系统架构,除非您选中了Show Metadata and Internal Schemas选项。

I did this to provide a quick way to ANALYZE an entire HOST or DB if needed or to run OPTIMIZE statements to support performance improvements.我这样做是为了提供一种快速的方法来在需要时ANALYZE整个主机或数据库,或者运行OPTIMIZE语句以支持性能改进。

I'm sure there are different ways you may go about doing this but here's what works for me:我敢肯定,您可以通过不同的方式来执行此操作,但以下是对我有用的方法:

-- ========================================== DYNAMICALLY FIND TABLES AND CREATE A LIST OF QUERIES IN THE RESULTS TO ANALYZE THEM
SELECT CONCAT('ANALYZE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname';

-- ========================================== DYNAMICALLY FIND TABLES AND CREATE A LIST OF QUERIES IN THE RESULTS TO OPTIMIZE THEM
SELECT CONCAT('OPTIMIZE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname';

Tested On MySQL Version: 5.6.23在 MySQL 版本上测试:5.6.23

WARNING: DO NOT RUN THIS IF:警告:如果出现以下情况,请勿运行:

  1. You are concerned with causing Table-locks (keep an eye on your client-connections)您担心导致表锁(注意您的客户端连接)
  2. You are unsure about what you are doing.你不确定你在做什么。

  3. You are trying to anger you DBA.您正试图激怒 DBA。 (you may have people at your desk with the quickness .) (你的办公桌上可能有人很快。)

Cheers, Jay ;-]干杯,杰伊;-]

This is the simple way that's i know.这是我所知道的简单方法。 Select your DB in PHPMyAdmin, and go to the "Search" tab and write what you want to find and where you will searching for.在 PHPMyAdmin 中选择您的数据库,然后转到“搜索”选项卡并写下您要查找的内容以及要搜索的位置。 Select all tables if you will search the words from all tables.如果您要从所有表格中搜索单词,请选择所有表格。 Then "GO" and look the result.然后“GO”并查看结果。 我想从我的 Wordpress DB 中找到单词 VCD(后门)以进行删除

使用 MySQL Workbench 可以轻松选择多个表并在数据库的所有这些表中搜索文本;-)

I also did my own mysql crawler to search some wordpress configuration, was unable to find it in both the interface and database, and database dumps were too heavy and unreadable.自己也做了mysql爬虫,搜索了一些wordpress的配置,界面和数据库都找不到,而且数据库转储太重,不可读。 I must say I can't do without it now.我必须说我现在离不开它。

It works like the one from @Olivier, but it manages exotic database / table names and is LIKE-joker safe.它的工作原理与@Olivier 的类似,但它管理异国情调的数据库/表名,并且是 LIKE-joker 安全的。

<?php

$database = 'database';
$criteria = '*iemblo'; // you can use * and ? as jokers

$dbh = new PDO("mysql:host=127.0.0.1;dbname={$database};charset=utf8", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$tables = $dbh->query("SHOW TABLES");
while (($table = $tables->fetch(PDO::FETCH_NUM)) !== false)
{
    $fields = $dbh->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?");
    $fields->execute(array ($database, $table[0]));

    $ors = array ();
    while (($field = $fields->fetch(PDO::FETCH_NUM)) !== false)
    {
        $ors[] = str_replace("`", "``", $field[0]) . " LIKE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(:search, '\\\\', '\\\\\\\\'), '%', '\\%'), '_', '\\_'), '*', '%'), '?', '_')";
    }

    $request = 'SELECT * FROM ';
    $request .= str_replace("`", "``", $table[0]);
    $request .= ' WHERE ';
    $request .= implode(' OR ', $ors);
    $rows = $dbh->prepare($request);

    $rows->execute(array ('search' => $criteria));

    $count = $rows->rowCount();
    if ($count == 0)
    {
        continue;
    }

    $str = "Table '{$table[0]}' contains {$count} rows matching '{$criteria}'.";
    echo str_repeat('-', strlen($str)), PHP_EOL;
    echo $str, PHP_EOL;
    echo str_repeat('-', strlen($str)), PHP_EOL;

    $counter = 1;
    while (($row = $rows->fetch(PDO::FETCH_ASSOC)) !== false)
    {
        $col = 0;
        $title = "Row #{$counter}:";
        echo $title;
        foreach ($row as $column => $value)
        {
            echo
            (($col++ > 0) ? str_repeat(' ', strlen($title) + 1) : ' '),
            $column, ': ',
            trim(preg_replace('!\s+!', ' ', str_replace(array ("\r", "\t", "\n"), array ("", "", " "), $value))),
            PHP_EOL;
        }
        echo PHP_EOL;
        $counter++;
    }
}

Running this script could output something like:运行此脚本可能会输出如下内容:

---------------------------------------------------
Table 'customers' contains 1 rows matching '*iemblo'.
---------------------------------------------------
Row #1: email_client: my@email.com
        numero_client_compta: C05135
        nom_client: Tiemblo
        adresse_facturation_1: 151, My Street
        adresse_facturation_2: 
        ville_facturation: Nantes
        code_postal_facturation: 44300
        pays_facturation: FR
        numero_tva_client: 
        zone_geographique: UE
        prenom_client: Alain
        commentaires: 
        nom_societe: 
        email_facturation: my@email.com

Although this question is old , here is how you can do it if you are using mysql workbench 6.3.虽然这个问题很老,但如果您使用的是 mysql workbench 6.3,这里是如何做到的。 ( Most likely it also works for other versions) (很可能它也适用于其他版本)

Right click your schema and "Search table data" , enter your value and hit "Start Search".右键单击您的架构和“搜索表数据”,输入您的值并点击“开始搜索”。 Thats it.而已。

This is the simplest query to retrive all Columns and Tables这是检索所有列和表的最简单查询

SELECT * FROM information_schema.`COLUMNS` C WHERE TABLE_SCHEMA = 'YOUR_DATABASE'

All the tables or those with specific string in name could be searched via Search tab in phpMyAdmin.可以通过 phpMyAdmin 中的“搜索”选项卡搜索所有表或名称中带有特定字符串的表。

Have Nice Query... \\^.^/有很好的查询... \\^.^/

Here is my solution for this这是我的解决方案

DROP PROCEDURE IF EXISTS findAll;
CREATE PROCEDURE `findAll`( IN `tableName` VARCHAR( 28 ) , IN `search` TEXT )
BEGIN
       DECLARE finished INT DEFAULT FALSE ;
       DECLARE columnName VARCHAR ( 28 ) ;
       DECLARE stmtFields TEXT ;
       DECLARE columnNames CURSOR FOR
              SELECT DISTINCT `COLUMN_NAME` FROM `information_schema`.`COLUMNS`
              WHERE `TABLE_NAME` = tableName ORDER BY `ORDINAL_POSITION` ;
       DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = TRUE;
       SET stmtFields = '' ;
       OPEN columnNames ;
       readColumns: LOOP
              FETCH columnNames INTO columnName ;
              IF finished THEN
                     LEAVE readColumns ;
              END IF;
              SET stmtFields = CONCAT(
                     stmtFields , IF ( LENGTH( stmtFields ) > 0 , ' OR' , ''  ) ,
                     ' `', tableName ,'`.`' , columnName , '` REGEXP "' , search , '"'
              ) ;
       END LOOP;
       SET @stmtQuery := CONCAT ( 'SELECT * FROM `' , tableName , '` WHERE ' , stmtFields ) ;
       PREPARE stmt FROM @stmtQuery ;
       EXECUTE stmt ;
       CLOSE columnNames ;
END;

I am use HeidiSQL is a useful and reliable tool designed for web developers using the popular MySQL server.我正在使用 HeidiSQL 是一个有用且可靠的工具,专为使用流行的 MySQL 服务器的 Web 开发人员设计。

In HeidiSQL you can push shift + ctrl + f and you can find text on the server in all tables.在 HeidiSQL 中,您可以按下 shift + ctrl + f,您可以在服务器上的所有表中找到文本。 This option is very usefully.这个选项非常有用。

MySQL Workbench MySQL 工作台

Here are some instructions.这里有一些说明。

Download and install MSQL Workbench.下载并安装 MSQL 工作台。

https://www.mysql.com/products/workbench/ https://www.mysql.com/products/workbench/

When installing, it might require you to install Visual Studio C++ Redistributable.安装时,可能需要安装 Visual Studio C++ Redistributable。 You can get it here:你可以在这里得到它:

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

x64: vc_redist.x64.exe (for 64 bit Windows) x64:vc_redist.x64.exe(适用于 64 位 Windows)

When you open MySQL Workbench, you will have to enter your host name, user and password.当您打开 MySQL Workbench 时,您必须输入您的主机名、用户名和密码。

There is a Schemas tab on the side menu bar, click on the Schemas tab, then double click on a database to select the database you want to search.侧面菜单栏上有一个 Schemas 选项卡,单击 Schemas 选项卡,然后双击一个数据库以选择要搜索的数据库。

Then go to menu Database - Search Data, and enter the text you are searching for, click on Start Search.然后转到菜单数据库 - 搜索数据,并输入您要搜索的文本,单击开始搜索。

在此处输入图片说明

HeidiSql海蒂数据库

Download and install HeidiSql https://www.heidisql.com/download.php下载并安装 HeidiSql https://www.heidisql.com/download.php

Enter your hostname, user and password.输入您的主机名、用户名和密码。

Hit Ctrl+Shift+F to search text.按 Ctrl+Shift+F 搜索文本。

在此处输入图片说明

This solution这个解决方案
a) is only MySQL, no other language needed, and a) 只是 MySQL,不需要其他语言,并且
b) returns SQL results, ready for processing! b) 返回 SQL 结果,准备处理!

#Search multiple database tables and/or columns
#Version 0.1 - JK 2014-01
#USAGE: 1. set the search term @search, 2. set the scope by adapting the WHERE clause of the `information_schema`.`columns` query
#NOTE: This is a usage example and might be advanced by setting the scope through a variable, putting it all in a function, and so on...

#define the search term here (using rules for the LIKE command, e.g % as a wildcard)
SET @search = '%needle%';

#settings
SET SESSION group_concat_max_len := @@max_allowed_packet;

#ini variable
SET @sql = NULL;

#query for prepared statement
SELECT
    GROUP_CONCAT("SELECT '",`TABLE_NAME`,"' AS `table`, '",`COLUMN_NAME`,"' AS `column`, `",`COLUMN_NAME`,"` AS `value` FROM `",TABLE_NAME,"` WHERE `",COLUMN_NAME,"` LIKE '",@search,"'" SEPARATOR "\nUNION\n") AS col
INTO @sql
FROM `information_schema`.`columns`
WHERE TABLE_NAME IN
(
    SELECT TABLE_NAME FROM `information_schema`.`columns`
    WHERE
        TABLE_SCHEMA IN ("my_database")
        && TABLE_NAME IN ("my_table1", "my_table2") || TABLE_NAME LIKE "my_prefix_%"
);

#prepare and execute the statement
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

You could use你可以用

SHOW TABLES;

Then get the columns in those tables (in a loop) with然后获取这些表中的列(在循环中)

SHOW COLUMNS FROM table;

and then with that info create many many queries which you can also UNION if you need.然后使用该信息创建许多查询,如果需要,您也可以 UNION。

But this is extremely heavy on the database.但这对数据库来说是非常沉重的。 Specially if you are doing a LIKE search.特别是在您进行 LIKE 搜索时。

It's been twelve years and no one posted an answer to the following question:十二年过去了,没有人发布以下问题的答案:

I want to search in all fields from all tables of a MySQL database for a given string我想在 MySQL 数据库的所有表的所有字段中搜索给定的字符串

Anwsers include GUIs, vague ideas, syntax errors, procedures needing table names or prefixes and all sorts of contortions. Anwsers 包括 GUI、模糊的想法、语法错误、需要表名或前缀的过程以及各种扭曲。 Here's an actual, working, tested, simple to use answer building on multiple previous answers but also adding the primary key to the results.这是一个实际的、有效的、经过测试的、易于使用的答案,它建立在多个先前的答案之上,但也将主键添加到结果中。

DROP PROCEDURE IF EXISTS findAll;
DELIMITER $$
CREATE PROCEDURE findAll( IN `search` TEXT )
BEGIN
    SET SESSION group_concat_max_len := @@max_allowed_packet;
    SELECT GROUP_CONCAT(
        "SELECT '", c1.TABLE_NAME, "' AS `table`, '", c1.COLUMN_NAME, "' AS `column`, ",
        "CONCAT_WS(',', ",  (SELECT GROUP_CONCAT(c2.column_name) FROM `information_schema`.`columns` c2 WHERE c1.TABLE_SCHEMA=c2.TABLE_SCHEMA AND c1.TABLE_NAME=c2.TABLE_NAME AND c2.COLUMN_KEY='PRI') ,") AS pri,", 
        c1.COLUMN_NAME, " AS value FROM ", c1.TABLE_NAME,
      " WHERE `",c1.COLUMN_NAME,"` LIKE '%", search, "%'" SEPARATOR "\nUNION\n") AS col 
    INTO @sql   
    FROM information_schema.columns c1 
    WHERE c1.TABLE_SCHEMA = DATABASE();
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;

That's it.就是这样。 You can now do CALL findAll('foobar');你现在可以做CALL findAll('foobar');

Except not.除了没有。 You will run into two problems:你会遇到两个问题:

  1. MySQL error 1436: Thread stack overrun MySQL 错误 1436:线程堆栈溢出
  2. Prepared statement needs to be re-prepared.准备好的语句需要重新准备。

Add the following two lines to /etc/mysql/mysql.conf.d/mysqld.cnf or wherever your cnf is or save them in a separate file and copy into the conf.d directory.将以下两行添加到/etc/mysql/mysql.conf.d/mysqld.cnfcnf所在的任何位置,或者将它们保存在单独的文件中并复制到conf.d目录中。

thread_stack            = 2M
table_definition_cache  = 5000

And yes, obviously this shouldn't be run on production because it's insecure and it'll tank your performance.是的,显然这不应该在生产中运行,因为它不安全并且会影响您的性能。

I modified the PHP answer of Olivier a bit to:我将 Olivier 的 PHP 答案修改为:

  • print out the results in which the string was found打印出找到字符串的结果
  • omit tables without results省略没有结果的表格
  • also show output if column names match the search input如果列名与搜索输入匹配,也显示输出
  • show total number of results显示结果总数

    function searchAllDB($search){ global $mysqli; $out = ""; $total = 0; $sql = "SHOW TABLES"; $rs = $mysqli->query($sql); if($rs->num_rows > 0){ while($r = $rs->fetch_array()){ $table = $r[0]; $sql_search = "select * from ".$table." where "; $sql_search_fields = Array(); $sql2 = "SHOW COLUMNS FROM ".$table; $rs2 = $mysqli->query($sql2); if($rs2->num_rows > 0){ while($r2 = $rs2->fetch_array()){ $colum = $r2[0]; $sql_search_fields[] = $colum." like('%".$search."%')"; if(strpos($colum,$search)) { echo "FIELD NAME: ".$colum."\\n"; } } $rs2->close(); } $sql_search .= implode(" OR ", $sql_search_fields); $rs3 = $mysqli->query($sql_search); if($rs3 && $rs3->num_rows > 0) { $out .= $table.": ".$rs3->num_rows."\\n"; if($rs3->num_rows > 0){ $total += $rs3->num_rows; $out.= print_r($rs3->fetch_all(),1); $rs3->close(); } } } $out .= "\\n\\nTotal results:".$total; $rs->close(); } return $out; }

I built on a previous answer and have this, some extra padding just to be able to conveniently join all the output:我建立在以前的答案的基础上,并有这个,一些额外的填充只是为了能够方便地加入所有输出:

SELECT 
CONCAT('SELECT ''',A.TABLE_NAME, '-' ,A.COLUMN_NAME,''' FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME, 
       ' WHERE ', A.COLUMN_NAME, ' LIKE \'%Value%\' UNION')
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE 
        A.TABLE_SCHEMA != 'mysql' 
AND     A.TABLE_SCHEMA != 'innodb' 
AND     A.TABLE_SCHEMA != 'performance_schema' 
AND     A.TABLE_SCHEMA != 'information_schema'
UNION SELECT 'SELECT '''

-- for exact match use: A.COLUMN_NAME, ' LIKE \'Value\' instead

First you run this, then paste in and run the result (no editing) and it will display all the table names and columns where the value is used.首先运行它,然后粘贴并运行结果(无编辑),它将显示使用该值的所有表名和列。

Even if the following proposal should not be considered as a final solution you can achieve the goal by doing something like this:即使以下建议不应被视为最终解决方案,您也可以通过执行以下操作来实现目标:

SET SESSION group_concat_max_len = 1000000;
SET @search = 'Text_To_Search';

DROP table IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS 
(SELECT 
    CONCAT('SELECT \'',TABLE_NAME,'\' as \'table_name\',\'',COLUMN_NAME,'\' as \'column_name\',CONVERT(count(*),char) as \'matches\' FROM `',
    TABLE_NAME,'` where `',COLUMN_NAME,'` like \'%',@search,'%\' UNION ') as 'query'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_name' limit 1000000);

set @query = (SELECT GROUP_CONCAT(t1.`query` SEPARATOR '') as 'final_query' from table1 t1 limit 1);
set @query = (SELECT SUBSTRING(@query, 1, length(@query) - 7));

PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Please remember that:请记住:

  1. Options: group_concat_max_len and limit 1000000 not always are needed, it will depends of your server/IDE configuration.选项: group_concat_max_lenlimit 1000000并不总是需要的,这取决于你的服务器/IDE 配置。 Just in case I added them.以防万一我添加了它们。

  2. After executing this you will get a 3 column response: [table_name], [column_name], [matches]执行此操作后,您将获得 3 列响应:[table_name]、[column_name]、[matches]

  3. Column 'matches' is the number of occurrences in the given table/column.列“匹配”是给定表/列中出现的次数。

  4. This query is very fast.这个查询非常快。

DISCLAIMER: It would be useful only for personal use, in other words please don't use it in a production system, because it is sensitive to SQL Injection attacks given that the search parameter is concatenated with other strings.免责声明:它仅对个人使用有用,换句话说,请不要在生产系统中使用它,因为鉴于搜索参数与其他字符串连接,它对 SQL 注入攻击很敏感。 If you want to create a prod.如果你想创建一个产品。 ready function, then you will need to create a store procedure with a LOOP. ready 函数,那么您将需要创建一个带有 LOOP 的存储过程。

i got this to work.我得到了这个工作。 you just need to change the variables你只需要改变变量

$query ="SELECT `column_name` FROM `information_schema`.`columns` WHERE `table_schema`='" . $_SESSION['db'] . "' AND `table_name`='" . $table . "' ";
$stmt = $dbh->prepare($query);
$stmt->execute(); 
$columns = $stmt->fetchAll(PDO::FETCH_ASSOC);       

$query="SELECT name FROM `" . $database . "`.`" . $table . "` WHERE ( ";
foreach ( $columns as $column ) {
    $query .=" CONVERT( `" . $column['column_name'] . "` USING utf8 ) LIKE '%" . $search . "%' OR ";
}
$query = substr($query, 0, -3);
$query .= ")";

echo $query . "<br>";
$stmt=$dbh->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r ($results );
echo "</pre>";

I have done this using HeidiSQL.我已经使用 HeidiSQL 做到了这一点。 It's not easy to find but by pressing Ctrl+Shift+F it displays the "table tools" dialogue.它不容易找到,但按 Ctrl+Shift+F 会显示“表格工具”对话框。 Then select what you want to search (Full database to single table) and enter the "Text to find" value and click "Find".然后选择要搜索的内容(完整数据库到单个表)并输入“要查找的文本”值并单击“查找”。 I found it surprisingly fast (870MiB db in less than a minute)我发现它非常快(不到一分钟就达到了 870MiB db)

I used Union to string together queries.我使用 Union 将查询串在一起。 Don't know if it's the most efficient way, but it works.不知道这是否是最有效的方法,但它有效。

SELECT * FROM table1 WHERE name LIKE '%Bob%' Union
SELCET * FROM table2 WHERE name LIKE '%Bob%';

There is a nice library for reading all tables, ridona有一个很好的图书馆可以阅读所有表格, ridona

$database = new ridona\Database('mysql:dbname=database_name;host=127.0.0.1', 'db_user','db_pass');

foreach ($database->tables()->by_entire() as $row) {

....do

}

I don't know if this is only in the recent versions, but right clicking on the Tables option in the Navigator pane pops up an option called Search Table Data .我不知道这是否只出现在最近的版本中,但右键单击Navigator窗格中的Tables选项会弹出一个名为Search Table Data的选项。 This opens up a search box where you fill in the search string and hit search.这会打开一个搜索框,您可以在其中填写搜索字符串并点击搜索。

You do need to select the table you want to search in on the left pane.您确实需要在左侧窗格中选择要搜索的表。 But if you hold down shift and select like 10 tables at a time, MySql can handle that and return results in seconds.但是,如果您按住 shift 并一次选择 10 个表,MySql 可以处理并在几秒钟内返回结果。

For anyone that is looking for better options!对于任何正在寻找更好选择的人! :) :)

In case 23 answers is not enough, here are 2 more... Depending on database structure and content, you may find one them to actually be a quick and simple solution.如果 23 个答案还不够,这里还有 2 个......根据数据库结构和内容,您可能会发现它们实际上是一种快速而简单的解决方案。

For fans of shell one-liners, here is a long one (actually on 2 lines to use variables):对于 shell one-liners 的粉丝,这里有一个很长的一个(实际上在 2 行上使用变量):

cmd='mysql -u Username -pYour_Password -D Your_Database' # <-- Adapt this

$cmd -s -e 'SHOW TABLES' | while read table; do echo "=== $table ==="; $cmd -B -s -e "SELECT * FROM $table" | grep 'Your_Search'; done

Or on multiple lines to make it more readable:或者在多行上使其更具可读性:

$cmd -s -e 'SHOW TABLES' \
| while read table; do
    echo "=== $table ===";
    $cmd -B -s -e "SELECT * FROM $table" \
    | grep 'Your_Search';
  done
  • -s ( --silent ) is to suppress the column name headers -s ( --silent ) 是抑制列名标题

  • -B ( --batch ) escapes special characters like newlines, so we get the whole record when using grep -B ( --batch ) 转义像换行符这样的特殊字符,所以我们在使用grep时会得到整个记录

And for Perl fans, this will let you use regular expressions:对于 Perl 爱好者,这将允许您使用正则表达式:

# perl -MDBI -le '($db,$u,$p)=@ARGV; $dbh=DBI->connect("dbi:mysql:dbname=$db",$u,$p); foreach $table ($dbh->tables()) {print "$table\n"; foreach $r ($dbh->selectall_array("SELECT * FROM $table")) {$_=join("\t", @$r); print $_ if (/Your_Regex/);}}' Your_Database Username Your_Password

Which in a "real" Perl script could be something like this:在“真正的”Perl 脚本中,它可能是这样的:

#!/usr/bin/perl

use strict;
use open qw(:std :utf8);

use DBI;

my $db_host  = 'localhost';
my $db       = 'Your_Database';
my $db_user  = 'Username';
my $db_pass  = 'Your_Password';

my $search    = qr/Your_regex_Search/;


# https://metacpan.org/pod/DBD::mysql
my $dbh = DBI->connect( "dbi:mysql:dbname=$db;host=$db_host", $db_user, $db_pass,
                        { mysql_enable_utf8mb4 => 1 }
) or die "Can't connect: $DBI::errstr\n";


foreach my $table ( $dbh->tables() ) {
    my $sth = $dbh->prepare("SELECT * FROM $table")
        or die "Can't prepare: ", $dbh->errstr;

    $sth->execute
        or die "Can't execute: ", $sth->errstr;

    my @results;

    while (my @row = $sth->fetchrow()) {
        local $_ = join("\t", @row);
        if ( /$search/ ) {
            push @results, $_;
        }
    }

    $sth->finish;

    next unless @results;

    print "*** TABLE $table :\n",
          join("\n---------------\n", @results),
          "\n" . "=" x 20 . "\n";
}

$dbh->disconnect;

To search a string in all tables in a database run the following command on CLI.要在数据库的所有表中搜索字符串,请在 CLI 上运行以下命令。

mysqldump -u UserName --no-create-info --extended-insert=FALSE DBName -p | grep -i "searchingString"

Or,要么,

mysqldump -u UserName --no-create-info --extended-insert=FALSE DBName -p | grep -i "searchingString" > searchingString.sql

If you are not using it on code level, you just want to check the information, you could export the entire database as SQL and then search on the text editor.如果你不是在代码级别使用它,你只是想查看信息,你可以将整个数据库导出为 SQL 然后在文本编辑器中搜索。

如果您使用的是phpMyAdmin遵循此答案 ,该站点可参考此内容

导出整个数据库并搜索.sql文件。

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

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