[英]Search a db for all tables that have a certain value in a column
Is it possible to search all tables in a DB for a certain value in a column? 是否可以在数据库的所有表中搜索列中的某个值? I have 30 tables in my DB.
我的数据库中有30张桌子。 Not all of them are using the FK employee_no.
并非所有人都使用FK employee_no。 Out of all the tables that do contain an employee_no column, not all tables will have a record entered for every employee.
在确实包含employee_no列的所有表中,并非所有表都会为每个雇员输入一条记录。
I would like to get a list of all the tables that contain the value 6172817 for the employee_no column. 我想获取所有包含employee_no列的值6172817的表的列表。
I know 我知道
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME like '%employee_no'
will return all the tables with the column name employee_no, but now I want all the tables with the value 6172817 for employee_No 将返回所有列名称为employee_no的表,但是现在我希望所有表employee_No的值为6172817
I have tried 我努力了
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE employee_no like '%6172817'
Is this possible? 这可能吗?
So this is what i got so far (made in postegresql though so you'll need to convert to mysql): 所以这就是我到目前为止(尽管是在postegresql中制作的,所以您需要转换为mysql):
DO $$
DECLARE
rowt text; -- cursor retun
rowf text; -- name of the current table that meets our requirement
rowfz text; -- formated rout
cr CURSOR FOR (SELECT t.table_name::text
FROM information_schema.tables t
INNER JOIN information_schema.columns c
ON c.table_name = t.table_name
AND c.table_schema = t.table_schema
WHERE c.column_name = 'employee_no' -- The column you're looking for here
AND t.table_schema NOT IN ('information_schema', 'my_db') -- Add any unwanted DB's
-- separated by comas
AND t.table_type = 'BASE TABLE'
ORDER BY t.table_name);
BEGIN
FOR rowt IN cr LOOP
rowfz := REPLACE (rowfz::text,'(','');
rowfz := REPLACE (rowfz::text,')','');
EXECUTE (concat(' SELECT ''',rowfz, ''' FROM ', rowfz,' WHERE ', rowfz,
'.employee_no LIKE '''%6172817''' ')) INTO rowf;
IF rowf IS NOT NULL -- prints out only the valid(not null) table names
RAISE NOTICE '%',rowf;
END IF;
END LOOP;
END $$;
This will tell you exactly what tables have what you want, however it won't be shown in a neat looking table(you might need to scroll through the result text). 这将准确告诉您哪些表具有所需的内容,但是不会在外观整洁的表中显示(您可能需要滚动显示结果文本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.