假设我有 3 个表,其中一个是父表,其他是子表
| Resource |
______________
| id |
| name |
|author |
_______________
| Movie |
_______________
|id
|lenght
|main actor
________________
| Book |
__________________
|id
|number of pages |
|Pubblisher |
___________________
现在我想做的是将三个表连接在一起启动 rs = stmt.executeQuery(sql) 检索所有数据,以便我传递的 sql 字符串可能是
sql= "SELECT * FROM Resource
LEFT JOIN Movie
LEFT JOIN BOOK
USING(id)
然后
while(rs.next())
{
//creating different objects with the data base on if its a movie or a book
..
}
我如何从我从哪个表进行的连接中知道结果行来自(电影或书籍),而不使用对属性(如
)的检查if(rs.getString("pubblisher").equals(NULL))
//creation of a movie
非常感谢!
最佳答案
不要使用SELECT *
。相反,您应该列出您希望查询返回的列;您可以使用 CASE
表达式来实现检查返回的列值的逻辑:
select
r.id resource_id,
r.name resource_name,
r.author resource_author,
m.length movie_length,
m.main_actor movie_main_actor,
b.number_of_pages book_number_of_pages,
b.publisher book_publisher,
case
when m.id is not null then 'movie'
when b.id is not null then 'book'
else 'none'
end src
from resource r
left join movie m on m.id = r.id
left join book b on b.id = r.id
此处的 src
列将包含 movie
、book
或 none
,具体取决于哪个 左连接
确实成功了。如果两个左连接
都有可能成功(考虑到您的设置,这似乎不太可能),那么您可以调整逻辑:
case
when m.id is not null and b.id is not null then 'both'
when m.id is not null then 'movie'
when b.id is not null then 'book'
else 'none'
end src
关于java - JDBC 将多个子表连接到父表,我如何知道结果行来自哪个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59825351/