如何从多个表中选择基于多对多关系?

问题描述:

我想创建一个select语句,它将根据两个表的条​​件返回一个特定用户的用户列表。我在我的数据库中创建了以下关系。 (进入10/10 MS油漆技能)
如何从多个表中选择基于多对多关系?

Table Design

我想例如输出什么,有以下添(跟随者)的用户,其中有users表中设置为0的通知。 从那里我可以做我想要的程序与结果。

到目前为止,我已经试过内部联接,

SELECT users.username FROM users 
INNER JOIN followers 
ON users.username = followers.followed 
WHERE followers.followed = users.username AND 
users.username = 'tim' 

,我似乎无法弄清楚如何将它正确格式。

+0

OK,编辑传入 – Pacified

+1

我包括我以前 – Pacified

如果您使用的不是'follow'字符串,'userid'而是'follower''followerid',会更清晰。

在这种情况下,在追随者表中将是userid = 1(tim user id)。

然后查询将是:

select * from users where notifications=0 and id in (select followerid from 
followers where userid=1) 

如果你需要坚持到结构:

select * from users where notifications=0 and username like (select follower from 
followers where followed like 'tim') 
+0

的方法,该问题是编程python抓取了用户名(它是一个bot),然后把这个名字插入到sql语句中。所以看起来我必须首先搜索与找到的名称相对应的id。 – Pacified

+0

我编辑以适应您的请求! – farbiondriven

+0

好吧,现在测试这个 – Pacified