首页 > 解决方案 > 选择表中的所有值加上返回 1/0 的列是否存在其他表中的记录

问题描述

我需要一些有关 MySQL 查询的帮助,这让我很头疼。

基本上我有两个相关的表。第一个表称为“书籍”,它包含有关书籍的基本信息。然后我有一个名为“user_books”的另一个表,它与前一个表和另一个表相关(与问题无关)。这是 books 表的样子:

| b_id       |    b_name     |   b_description    |
---------------------------------------------------
| 1          |    Book1      |   Description1     |
| 2          |    Book2      |   Description2     |

'user_books' 表有以下内容:

| ub_userid  | ub_bookid  | ub_rating  | ub_default  |
------------------------------------------------------
| 10         | 1          | 5          | 1           |

user_books 表有两个主键:ub_userid 和 ub_bookid。

现在我需要进行一个查询,该查询返回 books 表的所有书籍,并为每本书返回给定用户的评分和一个列,如果 user_books 表中有该书的记录,则返回 1 但如果没有t 任何具有该 bookid 的书都返回 0。

给定用户 10 我想要的输出是这样的:

| b_id  | b_name | b_description  | ub_default  | active |
----------------------------------------------------------
| 1     | Book1  | Description1   | 1           |  1     |
| 2     | Book2  | Description2   | 0           |  0     |
----------------------------------------------------------

我正在使用 MySQL 5.7

非常感谢您提供任何帮助。

标签: mysqlsql

解决方案


select 
  b.b_id, 
  b.b_name, 
  b.b_description, 
  coalesce(ub.ub_default, 0) as ub_default,
  case 
    when ub.ub_userid is null then 0 
    else 1 
  end as active  
from books b left outer join 
     user_books ub 
     on ub.ub_bookid = b.b_id
where
     ub.ub_userid = 10;

这不会进行任何聚合,因此如果一条记录有多个user_books记录books,则该books记录将被复制。但是,它显示了如何连接缺失的行(外连接)并测试该外连接行是否存在或缺失。

这是 MySQL 5.6 的 SQL Fiddle http://sqlfiddle.com/#!9/b70ff8/4/0


推荐阅读