java - JDBC 将多个子表连接到父表,我如何知道结果行来自哪个表?

标签 java mysql sql jdbc left-join

假设我有 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 列将包含 moviebooknone,具体取决于哪个 左连接 确实成功了。如果两个左连接都有可能成功(考虑到您的设置,这似乎不太可能),那么您可以调整逻辑:

    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/

相关文章:

java - IntelliJ 插件开发 : PluginException cannot create class Action

php - 更新两个表中的匹配列

java - Oracle Sql 中的正则表达式

php - 在一个 SQL 列中保存多个元素的好方法?

java - Hibernate - 如何在不映射到特定类的情况下执行命名 native 查询

php - WHILE 中的 IF 语句不起作用

java - Jasper 报告组件在 JavaFX Swing 节点中未正确呈现

java - 将文件(.zip、.jar、...)下载到文件夹

java - Appium Webdriver 导入问题

mysql - 为什么 MySQL 连接忽略 R 中的 SET NAMES utf8 指令?