我有专辑表和专辑许可表。
专辑 album_id 名称 私人(价值是或否)
相册权限 ID album_id USER_ID
**albums**
album_id name private
1 family yes
2 friend no
3 outdoor pic yes
**album permission**
id album_id user_id
1 3 5
现在我想获得所有专辑列表,我已获得许可。这意味着如果album.private = no或者我的id(5)存在于权限表中,那么该行应该在列表中,否则它不应该显示在列表中。
以下应该在结果中显示我
**albums result set**
album_id name private
2 friend no
3 outdoor pic yes -- < this showing me, because i exist in the permission table
答案 0 :(得分:3)
诀窍是保持对专辑权限的加入,这意味着将选择每个专辑,如果有与之关联的许可记录,则也会选择该记录。
然后只需添加一个where子句,表示相册不得为私有,或者应存在权限记录。
SELECT Albums.Album_ID, Albums.Name, Albums.Private
FROM Albums
LEFT JOIN AlbumPermissions ON Albums.Album_ID = AlbumPermissions.Album_ID
AND AlbumPermissions.User_ID = 5
WHERE
Albmums.private == 'no'
OR AlbumPermissions.ID IS NOT NULL
答案 1 :(得分:2)
select * from **albums** a
where a.private = 'no'
or exists (
select 1 from **album permission** p
where p.album_id = a.album_id
and p.user_id = 5
)
答案 2 :(得分:1)
使用UNION:
SELECT a.album_id,
a.name,
a.private
FROM ALBUMS a
WHERE a.private = 'no'
UNION ALL
SELECT a.album_id,
a.name,
a.private
FROM ALBUMS a
JOIN ALBUM_PERMISSION ap ON ap.album_id = a.album_id
WHERE ap.user_id = 5