Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在MySQL中获取foreignKey值的所有相关数据表_Mysql_Mariadb - Fatal编程技术网

如何在MySQL中获取foreignKey值的所有相关数据表

如何在MySQL中获取foreignKey值的所有相关数据表,mysql,mariadb,Mysql,Mariadb,我有很多桌子。在每个表中都有一个用户id作为指向user.id(用户表,主键)的外键。这用于记录哪些用户插入/更改了数据 现在我想知道用户在哪些表中插入了数据。 有没有一个不加入所有表的简单技巧 我不期望数据(可以稍后查询) 我不需要知道用户表的外键指向哪个表(我已经知道) 我想知道用户数据与何处相关 我可以加入所有表,但这将是一个巨大的性能问题。有很多桌子,有些也很大 我要找的东西是: SELECT tablename FROM information_schema.foo WHERE

我有很多桌子。在每个表中都有一个用户id作为指向user.id(用户表,主键)的外键。这用于记录哪些用户插入/更改了数据

现在我想知道用户在哪些表中插入了数据。 有没有一个不加入所有表的简单技巧

  • 我不期望数据(可以稍后查询)
  • 我不需要知道用户表的外键指向哪个表(我已经知道)
  • 我想知道用户数据与何处相关
我可以加入所有表,但这将是一个巨大的性能问题。有很多桌子,有些也很大

我要找的东西是:

SELECT tablename 
FROM information_schema.foo 
WHERE foreign_key = "key_name" AND foreign_key_value = 2;
select 'employees' as `in_table`, IF (user_id IS NOT NULL, 'Present', 'Absent') as exist from employees where user_id = 2; 
select 'profile_documents' as `in_table`, IF (user_id IS NOT NULL, 'Present', 'Absent') as exist from profile_documents where user_id = 2; 

我不认为有任何直接的方法,但您可以使用
信息\u模式.key\u column\u用法
为您构建查询

SELECT 
  concat('select \'',TABLE_NAME,
  '\' as `in_table`, IF (',COLUMN_NAME,' IS NOT NULL, \'Present\', \'Absent\') as exist from ',
 TABLE_NAME, ' where ', COLUMN_NAME, ' = 2; ') as `query`
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = 'testdb' AND
  REFERENCED_TABLE_NAME = 'users';
现在您有了上面的查询,它将返回对
user id=2
的每个表的查询。 您可以创建一个以用户id为参数的过程,然后执行上述查询

循环遍历结果,如:

SELECT tablename 
FROM information_schema.foo 
WHERE foreign_key = "key_name" AND foreign_key_value = 2;
select 'employees' as `in_table`, IF (user_id IS NOT NULL, 'Present', 'Absent') as exist from employees where user_id = 2; 
select 'profile_documents' as `in_table`, IF (user_id IS NOT NULL, 'Present', 'Absent') as exist from profile_documents where user_id = 2; 
然后一个一个地执行

然后使用该过程返回存在用户信息的表的名称