所以最初我把它作为试运行。
SELECT DISTINCT table_schema FROM information_schema.columns WHERE table_schema LIKE '%or';
我环顾四周,发现查询显示包含特定表的所有数据库。
但是,可以让查询更进一步,并执行以下操作:
“选择所有那些在其中包含特定表的数据库,并在该表中,在特定列中具有特定记录。”?
答案 0 :(得分:0)
您无法使用SQL语句执行所需操作。
但是,您可以使用SQL生成所需的语句。基本陈述是:
select "tablename"
from tablename
where columnname = value
limit 1
请注意,值可能需要在其周围加上单引号。您可以使用以下命令生成此内容:
select concat('select "', c.table_name, '" ',
'from ', c.schema_name, '.', c.table_name, ' ',
'where ', c.column_name, ' = ', VALUE, ' '
'limit 1'
)
from information_schema.columns c
where c.table_name = TABLENAME and c.column_name = COLUMN_NAME;
要将所有语句放在一个长SQL语句中,请使用:
select group_concat(concat('select "', c.table_name, '" as table_name',
'from ', c.schema_name, '.', c.table_name, ' ',
'where ', c.column_name, ' = ', VALUE, ' '
'limit 1'
) SEPARATOR ' union all '
)
from information_schema.columns c
where c.table_name = TABLENAME and c.column_name = COLUMN_NAME;
然后我会复制生成的SQL语句并运行它。如果您愿意,可以添加prepare
语句并动态运行。
答案 1 :(得分:0)
举个例子, 我有一个名为T1的表(C1,C2),我正在搜索'Needle'这个值。
这个存储过程的作用是搜索以T开头的表名和以C开头的列,然后遍历它们并找到值“Needle”。然后它返回table_Schema,table_name,column_name以及在column_name,table_name,table_schema组合中找到“Needle”值的次数。
请参阅此sqlFiddle
CREATE PROCEDURE findDatabase(IN in_value varchar(50))
BEGIN
DECLARE bDone INT;
DECLARE _TableSchema VARCHAR(50);
DECLARE _TableName VARCHAR(50);
DECLARE _ColumnName VARCHAR(50);
DECLARE curs CURSOR FOR SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME LIKE "T%" AND COLUMN_NAME LIKE "C%";
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
id int auto_increment primary key,
tableSchema varchar(50),
tablename varchar(50),
columnname varchar(50),
timesFound int
);
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO _TableSchema,_TableName,_ColumnName;
SET @found = 0;
SET @sql = CONCAT("SET @found = (SELECT COUNT(*) FROM ",_TableSchema,".",_TableName,
" WHERE ",_ColumnName,"='",in_value,"')");
PREPARE statement FROM @sql;
EXECUTE statement;
IF (@found > 0) THEN
INSERT INTO tblResults(tableSchema,tableName,columnName,TimesFound) VALUES (_TableSchema,_TableName,_ColumnName,@found);
END IF;
UNTIL bDone END REPEAT;
CLOSE curs;
SELECT DISTINCT TableSchema,TableName,ColumnName,TimesFound FROM tblResults;
DROP TABLE tblResults;
END//