簡體   English   中英

JDBC JOINing 多個子表到父表,我怎么知道結果行來自哪個表?

[英]JDBC JOINing multiple child tables to a parent table, how can i know from which table is the resulting row?

假設我有 3 張桌子,一張是父母,其他是孩子

| Resource   |
______________
| id          |
| name        |
|author       |
_______________


|  Movie      |
_______________
|id
|lenght
|main actor
________________


| Book           |
__________________
|id
|number of pages  |
|Pubblisher       |
___________________

現在我想做的是將三個表連接在一起啟動 rs = stmt.executeQuery(sql) 來檢索所有數據,以便我傳遞的 sql String 可能是

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 ,具體取決於哪個left join成功。 如果兩個left join都可能成功(考慮到您的設置,這似乎不太可能),那么您可以調整邏輯:

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM