mysql - 选择表中的所有值加上返回 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
非常感谢您提供任何帮助。
解决方案
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
推荐阅读
- docker - 如何通过 ssh 和 docker 将一些图形化 sql 工具连接到数据库
- android - 如何在 android 上使用 react-native-batch-push?尝试访问 RNBatch.NOTIFICATION_TYPES 时未定义 RNBatch
- angular - Angular 解析器得到一个 Observable
- r - 将 DF 的结构更改为 dummy
- git - Git 还原
不适用于本地并在代码中添加行 - java - 如何在 21-AndroidX 以下的 api 上使用 Cardview
- drools - OptaPlanner:Drools 对连续班次分配的规则
- string - 如何传递 &mut str 并更改原始 mut str 而不返回?
- php - Laravel Sanctum 默认模型定制
- javascript - 更新内容后 Javascript 功能不起作用(使用 Document Ready atm。)