检查连接结果集是否包含SQL中的某个值

时间:2014-03-13 16:04:58

标签: mysql sql

我有一个与此类似的数据库结构:

asset
+----+---------+
| id | user_id |
+----+---------+

user_favorite
+----------+---------+
| asset_id | user_id |
+----------+---------+

我希望创建一个查询,我可以返回属于给定用户的所有资源和一个布尔值,指示它是否是他们的“最爱”。

我可以做到这一点,其中count()等于零意味着它不是最喜欢的(但它似乎是hacky和低效):

select distinct(a.asset_id), 
    (select count(*) 
     from user_favorite f 
     where f.user_id = MY USER ID 
       and f.asset_id = a.asset_id) 
from asset a 
left join user_favorite u on a.asset_id=u.asset_id 
where a.user_id = MY USER ID;

我试过这个(但是当多个用户对它们进行了收藏时,它从资产中产生了多个条目:

select distinct (a.asset_id), 
    (u.user_id in (MY USER ID)) 
from asset a 
left join user_favorite u on a.asset_id=u.asset_id 
where a.user_id = MY USER ID;

我也试过了(但IN条件没有得到遵守):

select distinct(a.asset_id), 
    (u.user_id in (MY USER ID)) 
from asset a 
left join user_favorite u on a.asset_id=u.asset_id 
where a.user_id = MY USER ID group by u.user_id;

有什么好方法可以进行此查询吗?

2 个答案:

答案 0 :(得分:1)

我就是这样做的,但我确信有很多可以接受的方式:

SELECT DISTINCT a.asset_id 
    ,CASE WHEN u.asset_id IS NULL 
          THEN 0 
          ELSE 1 
     END AS IsFavourite
FROM asset a
LEFT JOIN user_favourite u ON a.asset_id = u.asset_id 
                           AND a.user_id = u.user_id
WHERE a.userid = MY_USER_ID

LEFT JOIN收藏于资源,如果没有收藏记录(u.asset_id IS NULL),那么它不是最喜欢的,否则就是。

答案 1 :(得分:0)

也许这会有所帮助

select 
     assetid,
     case when isnull(fav.user_id,0) =1 Then 0 else 1 end
form
     asset a
     left outer join 
     user_favourite fav
     on a.user_id = fav.user_id
where
     fav.id = 'foobar'
GROUP BY assetid, fav.user_id