我如何加入这两张桌子?
休息表
+----+-------------+
| id | description |
+----+-------------+
| 1 | Sample |
| 2 | Sample 2 |
+----+-------------+
用户收藏夹
+----+---------+-----------+
| id | user_id | breaks_id |
+----+---------+-----------+
| 1 | 2 | 1 |
+----+---------+-----------+
我的预期输出
+-----------+----------+--------------+-------------+
| breaks_id | user_id | is_favorite | description |
+-----------+----------+--------------+-------------+
| 1 | 2 | 1 | Sample |
| 2 | null | null | Sample |
+-----------+----------+--------------+-------------+
我想查看user_id = 1的所有休息列表,如果不是收藏夹,则查看null
答案 0 :(得分:1)
我想你只想在这里使用OUTER JOIN:
SELECT b.id AS break_id, f.user_id, f.id AS is_favorite, b.description
FROM breaks b
LEFT JOIN
user_favorites f
ON b.id = f.breaks_id;
LEFT JOIN是一个外部联接,它将从中断表中选择所有记录,并将它们与user_favorites表中的相应条目连接起来。如果没有匹配项,相关字段将为空。
答案 1 :(得分:1)
它会起作用
SELECT br.id AS break_id, fv.user_id, fv.id AS is_favorite,
br.description
from breaks br
left join favorites fv
on br.id = fv.id
where fv.id is null;