SQL -

2015-08-28 47 views
0

我目前使用下面的查詢來連接兩個表一起簡化聯合查詢:SQL -

select distinct book_id, clean_page_content as page_content, 'clean' as status, reg_date 
from book_db_clean_pages t 
where book_id = 'sarafi_book_5' 
and reg_date = '2015-08-26' 

UNION all 

select distinct book_id, dirty_page_content as page_content, 'dirty' as status, reg_date 
from book_db_dirty_pages e 
where book_id = 'sarafi_book_5' 
and reg_date = '2015-08-26' 

然而,當我想尋找一個不同的book_id我需要改變兩個分句(一個在上面,一個低於UNION)。同樣的原則適用於reg_date。所以我想知道是否有可能簡化我的查詢只是使用可能的命令,如加入或其他事情。原則上,我要尋找一個解決方案這樣:

select distinct t.book_id, (t.clean_page_content or e.dirty_page_content) as page_content, 
     ('clean' or 'dirty') as status, t.reg_date 
from book_db_clean_pages t, book_db_dirty_pages e 
where t.book_id = e.book_id and t.reg_date = e.reg_date 
and t.book_id = 'sarafi_book_5' 
and t.reg_date = '2015-08-26' 
+2

無論如何UNION,無論如何刪除所有副本都不需要做SELECT DISTINCT。 – jarlh

+0

你有什麼看法並從中選擇? –

回答

2

把你的工會成派生表:

select * 
from (
    select ... 
    from book_db_clean_pages t 
    -- no where clause 

    union all 

    select ... 
    from book_db_dirty_pages e 
    where t.book_id = e.book_id and t.reg_date = e.reg_date 
    -- no where clause for book_id and reg_date 

) t 
where book_id = 'sarafi_book_5' 
and reg_date = '2015-08-26'; 

所有現代DBMS將是足夠的智慧來推動的條件爲派生表,所以當你這樣做的時候不應該有性能損失。


順便說一句:如果book_id是主鍵(或唯一的列)的兩個表中,施加在內部選擇distinct不會移除任何東西。

+0

你的順便說一句對我來說毫無意義。如果'distinct'不會刪除任何東西,'union'也不會因爲每個聯合部分的狀態列不同而不同。 –

+0

@Aツ:聯合會刪除_overall result_中的重複項,例如當book_id(假設_is_是主鍵)出現在具有相同屬性的兩個表中時。這與單獨刪除每個查詢結果中的重複項有所不同(如果'book_id'在這些表中是唯一的,這可能不會發生) –

+0

op在聯合的每個部分中定義了不同的狀態。這確保了行是不同的。 –

0

你不能簡化查詢,因爲你已經寫了它。

你可以寫:

select distinct b.* 
from ((select book_id, clean_page_content as page_content, 'clean' as status, reg_date 
     from book_db_clean_pages t 
    ) union all 
     (select book_id, dirty_page_content as page_content, 'dirty' as status, reg_date 
     from book_db_dirty_pages e 
    ) 
    ) b 
where book_id = 'sarafi_book_5' and reg_date = '2015-08-26'; 

你沒有提到你正在使用的數據庫。如果子查詢可以使用索引,那麼您的初始查詢可能會更有效率。