包含所有行的两个表,包括基于id的分配

时间:2017-02-12 16:18:12

标签: mysql join union

我试图使这个通用,因为它可能在将来帮助其他人。

例如,我有两个表,一个有书,另一个是用户已经阅读过的书,所以想要显示所有书籍,并将临时列值包含为(是/否或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

2 个答案:

答案 0 :(得分:1)

这实际上非常简单。如果用户可以多次阅读图书,我会在exists中使用select

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中,case并不是绝对必要的,因为在许多上下文中布尔表达式被视为0/1:

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;

答案 1 :(得分: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
相关问题