我尝试为包含用户之前选择的分组复选框的表单创建数据。为了准备数据,我试图从我的复选框可见性表中返回所有行,并添加一个额外的列,指示可见性表中的行是否出现在数据透视表users_visibility中。我该怎么做呢?
这就是我所拥有的。它根据用户的id返回两个表的共同点。
select
visibility.id as visibility_id,
visibility.title as visibility_title,
users_visibility.users_id as checked
from visibility
left join users_visibility on users_visibility.visibility_id = visibility.id
where users_visibility.users_id = 2
表示例
visibility
=======================
id title
-----------------------
1 Drivers licence
2 No Criminal record
3 Senior volunteer
users_visibility
===========================
id users_id visibility_id
---------------------------
1 2 3
我想要归还
========================================
visibility_id visibility_title checked
----------------------------------------
1 Drivers licence NULL
2 No Criminal record NULL
3 Senior volunteer 2 (user_id or whatever indicator)
感谢。
答案 0 :(得分:1)
对于left join
,除第一个表外的所有条件都应该在on
子句中。
表别名也可以使查询更容易编写和阅读:
select v.id as visibility_id, v.title as visibility_title,
uv.users_id as checked
from visibility v left join
users_visibility uv
on uv.visibility_id = v.id and uv.users_id = 2;