Search in all fields from every table of a MySQL d

2018-12-31 08:58发布

I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:

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

Is it possible to do something like this?

标签: mysql
24条回答
裙下三千臣
2楼-- · 2018-12-31 09:45

Dumping the SQL file was probably the quickest and fastest for me. Also discovered another problem anyways..

查看更多
骚的不知所云
3楼-- · 2018-12-31 09:45

I used Union to string together queries. 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%';
查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 09:45

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>";
查看更多
浮光初槿花落
5楼-- · 2018-12-31 09:47

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.

Have Nice Query... \^.^/

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 09:47

Using MySQL Workbench it's easy to select several tables and run a search for text in all those tables of the DB ;-)

查看更多
人间绝色
7楼-- · 2018-12-31 09:54

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.

查看更多
登录 后发表回答