如何获取外键使用的表名

时间:2012-06-28 02:08:25

标签: mysql jpa entity primary-key

我使用了JPA和mysql。 每个表都有实体类。我有四个表。

表1:student_table

studentId(PK), studentName 
1              jack
2              robert
3              tom
4              smith   

表2:roll_table

rollId(PK), studentId(FK) 
10001          1
10002          2
10003          3
10004          4

表3:address_table

addressId(PK)  City          studentId(FK) 
1               Washngton       1
2               NewYork1        2
3               Newyork2        3
4               Wasington2      4

表4:contact_table

------------------------------------------------
contactId(pk) phoneNumber email studentId(FK) 
------------------------------------------------

----------------------------------------------

基表是'student_table'。 'studentId'是此表的主键。

剩下的3个表使用了这个studentId作为外键。 总共3个表包含数据。一张表没有任何数据。

我需要编写查询“studentId = 2使用的表名和表如果数据存在于其他表中则计数。 否则有任何其他逻辑来获取此信息。

现在,studentId = 2使用了两张桌子。结果是*(roll_table,address_table)*
假设联系表包含studentId = 2的数据, 然后结果是*(roll_table,address_table,contact_table)*

帮帮我。 提前致谢

2 个答案:

答案 0 :(得分:0)

尝试使用left join来帮助您显示lefttable(studentName)中的所有记录,即使右表没有匹配项(roll_table,address_table,contact_table)

    SELECT student_table.studentId,student_table.studentName
 FROM student_table
 LEFT JOIN roll_table ON student_table.studentId = roll_table.studentId
 LEFT JOIN address_table ON student_table.studentId = address_table.studentId
 LEFT JOIN contact_table ON student_table.studentId = contact_table.studentId

答案 1 :(得分:0)

尝试此查询

SELECT * FROM information_schema.KEY_COLUMN_USAGE 
         WHERE REFERENCED_TABLE_NAME = 'Your base table name'
         AND TABLE_SCHEMA='DataBaseName' 
         AND REFERENCED_COLUMN_NAME = 'coloumnName'

实施例

 SELECT * FROM information_schema.KEY_COLUMN_USAGE 
         WHERE REFERENCED_TABLE_NAME = 'student_table'
         AND TABLE_SCHEMA='student_dataBase' 
         AND REFERENCED_COLUMN_NAME = 'studentId'