不要在第二个表映射列数据的表中选择该行

时间:2016-12-14 14:18:26

标签: mysql sql

我想从两个表中得到结果。表格如下: -

表1:标签 -

tagid          tagname

 1            science
 2            technology
 3            art
 4            culture
 5            space
 6            fashion

表2: usersAndTags

tagid          userid

 6               23
 2               97
 4               23
 4               97
 3               56
 6               23

tags包含tagidtagname。表格userAndTags包含tagiduserid。一行userAndTags显示具有该用户标识的用户跟随该标记。

我希望表tagname中的tagidtags没有被userid跟踪.23。什么是sql查询。

2 个答案:

答案 0 :(得分:2)

您可以使用not exists

执行此操作
select *
from tags t
where not exists (select 1 from usersandtags 
                  where t.tagid=tagid 
                  and userid=23)

left join

 select t.*
 from tags t
 left join usersandtags u on u.tagid=t.tagid and u.userid=23
 where u.tagid is null

答案 1 :(得分:2)

你可以LEFT JOIN喜欢

select t.tagid,
t.tagname
from tags t
left join usersAndTags ut on t.tagid  = ut.tagid          
and ut.userid = 23
where ut.tagid is null;