2012-06-28 40 views
0

我使用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)*

帮助我。 谢谢提前

+0

了解[SQL连接(http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins .html):你想使用外部连接。 – eggyal

回答

0

试着左加入,帮助您从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 
+0

感谢您的回复。假设我在1000个表中使用了外键...我需要添加更多的行数query.is对不对? – jackrobert

+0

我希望studentId只使用表名(存在数据),当执行查询时。这里有3个表引用studentId。但两个表格数据指向student_table。在将来我不知道,有多少表引用studentId – jackrobert

+0

在这种情况下使用内部连接,而不是左连接,只有当显示匹配的学生ID – mintokyo

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' 
+0

谢谢埃斯瓦尔。但是当我执行这个查询时,它返回所有的表名。 (它也包含空表名)。如果数据存在,我需要表格名称。 – jackrobert