【问题标题】:How to get foreign key used tablenames如何获取外键使用的表名
【发布时间】:2012-06-28 02:08:25
【问题描述】:

我使用了 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:地址表

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)*

帮帮我。 在此先感谢

【问题讨论】:

标签: mysql jpa entity primary-key


【解决方案1】:

尝试左连接,它可以帮助您显示左表(学生姓名)中的所有记录,即使右表(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

【讨论】:

  • 感谢您的回复。假设我在 1000 个表中使用了外键...我需要添加更多行数查询。对吗?
  • 我希望studentId在执行查询时只使用表名(数据存在)。这里有3个表引用studentId。但是两个表数据都指向student_table。以后我不知道,有多少表是指那个studentId
  • 在这种情况下,使用 Inner Join 而不是 Left join,仅当有匹配的 studentID 时才会显示
【解决方案2】:

试试这个查询

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'

【讨论】:

  • 谢谢埃斯瓦尔。但是当我执行这个查询时,它会返回所有的表名。 (它也包含空表名)。如果数据存在,我需要表名。
猜你喜欢
  • 2020-06-14
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多