我有两个表:
tbl书籍:BookID,标题
tbl收藏夹:FavoriteID、UserID、BookID
我想开发一个SQL查询来选择BookID、Title、IsFavorite(true|false(,同时将UserID作为参数。
Foreach BookID应该检查tblFavorite中是否有一行包含此BookID和给定的UserID->真/假
您可以使用相关的子查询:
select b.*,
case when exists (select 1 from tblfavorite f where f.bookid = b.bookid and f.userid = ?)
then 1
else 0
end as isfavorite
from tblbook b
问号表示生成报告的用户的id。在支持将条件求值为布尔值或整数的数据库中(例如MySQL或Postgres(,可以分配case
表达式:
select b.*,
exists (select 1 from tblfavorite f where f.bookid = b.bookid and f.userid = ?) as isfavorite
from tblbook b
使用LEFT JOIN和CASE表达式,这样,如果tblFavorite(NULL(中没有记录,则显示False,否则显示True。
SELECT B.BookID, B.Title, CASE WHEN FavoriteID IS NULL THEN 'False' ELSE 'True' END AS IsFavorite
FROM tblBook B
LEFT JOIN tblFavorite F on B.BookID = F.BookID