2017-02-12 73 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 
相关问题