如何获取链接到外键值的InnoDB表名?

时间:2019-06-20 06:04:14

标签: mysql innodb

我有多个表(例如:带有外键ADDRESS_ID的A,B,C ....等)链接到“地址”表,其中ADDRESS_ID是主键。表A,B,C ...可能具有或没有address_ID值。是否有一个查询,我可以获取地址表中具有给定ADDRESS_ID的表名?请注意,这不是“地址”表中给定列的表名。如果地址表中给定的 Address_ID值,我已经需要表名了,如果其他表中已经引用了它。 (我不知道可能引用了address_id的所有表。)

Address table 
ADDRESS_ID (PK) |   STREET ADDRESS_1   |   STREET_ADDRESS_2  |   CITY  |  ZIPCODE    


Table A
A_ID  |  ADDRESS_ID (FK) |  FIELD _1  |   FIELD_2

Table B
B_ID  |  ADDRESS_ID (FK)|  FIELD _!  |  FIELD_2

Table C
B_ID  |  ADDRESS_ID (FK) |  FIELD _! |  FIELD_2

更多表格...

这是我尝试过的:

SELECT * FROM information_schema.TABLE_CONSTRAINTS 
WHERE 
information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' AND
TABLE_CONSTRAINTS.TABLE_SCHEMA = 'flower_db' AND
TABLE_CONSTRAINTS.TABLE_NAME = 'address';

但这不支持我真正想要的。

2 个答案:

答案 0 :(得分:0)

 SELECT 'TableA' as Table_Has_Address       
 FROM TableA
 GROUP BY ADDRESS_ID
 HAVING COUNT(CASE WHEN ADDRESS_ID = @address_id THEN 1 END) > 0

 UNION ALL

 SELECT 'TableB' as Table_Has_Address       
 FROM TableB
 GROUP BY ADDRESS_ID
 HAVING COUNT(CASE WHEN ADDRESS_ID = @address_id THEN 1 END) > 0

 UNION ALL

 SELECT 'TableC' as Table_Has_Address       
 FROM TableC
 GROUP BY ADDRESS_ID
 HAVING COUNT(CASE WHEN ADDRESS_ID = @address_id THEN 1 END) > 0

答案 1 :(得分:0)

SELECT *
    FROM information_schema.REFERENTIAL_CONSTRAINTS
    WHERE REFERENCED_TABLE_NAME = 'address'

(根据需要调整查询)