2017-02-12 72 views
0

我試圖使其具有通用性,因爲它可能會在未來幫助其他人。包含所有行的兩個表格,包括基於ID分配的內容

舉個例子,我有兩個表格,一個是書本,另一個是用戶,他們已經閱讀了哪本書,所以ide喜歡顯示所有的書籍,並且包含一個臨時列值作爲(yes/no或0/1),我試過了一個連接,但是(WHERE user_id = 3)子句只返回一行而不是所有其他行。

book.book_id  book.book_name 
    10     Book 1 
    11     Book 2 
    12     Book 3 

------------- 

user.user_id user.book_id 
     1     10 
     1     12 
     2     11 
     3     12 


Desired output: 

user_id  book_id  temp_col_read 
     3   10   0 // yes, on or null 
     3   12   1 // or yes 
     3   13   0 
+0

你需要一個'LEFT OUTER JOIN'的日是案例 –

+0

@SamiKuhmonen,對不起,我的問題沒有任何我已經嘗試過的例子。左外連接不起作用。 – david

回答

1

這其實很簡單。在此用戶可以讀一本書多次的情況下,我會去existsselect

select b.*, 
     (case when exists (select 1 
          from reads r 
          where r.book_id = b.book_id and r.user_id = 3 
         ) 
      then 1 else 0 
     end) as user_read_book 
from book b; 

在MySQL中,因爲布爾表達式中多達0/1對待case並非絕對必要背景:

select b.*, 
     (exists (select 1 
       from reads r 
       where r.book_id = b.book_id and r.user_id = 3 
     ) as user_read_book 
from book b; 
+0

是的,用戶可以多次使用存在選擇工作讀取書籍,謝謝。 – david

1

您可以使用左連接,並在連接是尚未解決的則無法讀取

select 
     user.user_id 
     , book.book_id 
     , case 
      when book.book_id is null 
       then 'NO' else 'YES' 
     end as temp_col_read 
    from book 
    left join user on user.book_id = book.book_id 
相關問題