请教这个需求的SQL怎么写,谢谢!

2013-10-20 11:51:25 +08:00
 gaolinjie
表 follow
+----+---------+------------+---------------------+
| id | user_id | channel_id | created |
+----+---------+------------+---------------------+

表 channel
+----+---------+------------+---------------------+
| id | name | created |
+----+---------+------------+---------------------+

现在需要
1. 先从 follow 表中选择 user_id=xxx 的所有记录,
2. 然后再从原来的 follow 表中选出 channel_id 不等于1步骤中选出的所有记录的 channel_id 的记录
3. 最后从 channel 表中选出所有 id 和2步骤中选出的记录的 channel_id 相等的记录

请教只用一句的SQL语句怎么写? 谢谢!
2306 次点击
所在节点    问与答
4 条回复
yangqi
2013-10-20 12:08:53 +08:00
SELECT id FROM channel WHERE channel_id IN ( SELECT channel_id FROM follow WHERE user_id != 'xxx' )
zxy
2013-10-20 12:17:09 +08:00
很久没写了,不知对错,还望指正
1、若channel_id 不重复,应该可以用这个
select *
from
channel
where channel_id in (select chnnel_id from follow where user_id <>'xxx')
2、若channel_id 重复,改为
select *
from
channel
where channel_id in
(select chnnel_id
from
follow
where channel_id not in
(select
channel_id
from
follow
where user_id ='xxx')
yangqi
2013-10-20 12:52:42 +08:00
读了N遍终于看懂楼主的意思了, 你给的步骤太复杂了,

直接 SELECT id FROM channel WHERE channel_id NOT IN ( SELECT channel_id FROM follow WHERE user_id = 'xxx' )
thinkif
2013-10-20 13:09:04 +08:00
select id, name, created from channel where exists(select 1 from follow where follow.channel_id = channel.id and user_id<>'xxx')

用 exists 比 In 快些

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/86176

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX