没办法了,又一个通宵了。

2014-12-04 07:31:21 +08:00
 p8p8
在postgresql里,A用户有好友C和D,A想获取除C和D之外的其他用户,但是A的好友可能有多个,E、F、G可能都是A的好友。该如何做呢?
4228 次点击
所在节点    Python
13 条回复
ivanlw
2014-12-04 07:32:56 +08:00
能post一下表的结构会更好一些……
O14
2014-12-04 07:47:03 +08:00
可能是 SELECT * FROM users,friends WHERE friends.user_id=users.id and friends.id!=C and friends.id!=D

请贴出表之间的关系
p8p8
2014-12-04 07:53:22 +08:00
我大概的说一下,有两个表,T1和T2,我从T2里去获取用户数据,但是这些用户数据,要在T1里,没有的。
datou552211
2014-12-04 08:19:24 +08:00
难道你有职能相同的两个表?
p8p8
2014-12-04 08:19:38 +08:00
query_mid = 'SELECT mid, nickname, avatar_url FROM users NOT IN (SELECT eid FROM rosterusers WHERE username = %s AND subscription != "F" ' \
'AND subscription != "T" AND subscription != "N");'

我想表达的意思是,得到users表中,所有rosterusers表里username != xx和 subscription != "F" ' \
'AND subscription != "T" AND subscription != "N"的数据。
O14
2014-12-04 08:25:01 +08:00
@p8p8 maybe 在FROM users 和NOT IN之间加个WHERE users.id

mid和eid表示的一个属性吗?
Narcissu5
2014-12-04 08:59:40 +08:00
left join + is null
tottichenzp
2014-12-04 09:02:56 +08:00
not exists 或者 not in
前者适用大表驱动小表,后者适用小表驱动大表
1314258
2014-12-04 09:14:25 +08:00
可以用python的集合。
MadbookPro
2014-12-04 10:12:12 +08:00
这种事让Neo4j做会好很多吧?
ispinfx
2014-12-04 10:25:59 +08:00
好像前10楼都把标题无视了……果然一谈技术就废寝忘餐……
yueyoum
2014-12-04 17:01:07 +08:00
刚好最近在学习postgresql,就来解答一下

LZ这样的 没有表结构, 怎么回答?

那我就来假设吧:


如果是经典的关系表:
那么你会有两个表, user 和 friends,

user 记录用户, friends 记录好友关系


mydb=# \d user
Table "public.user"
Column | Type | Modifiers
--------+---------+-----------
id | integer

mydb=# \d friends
Table "public.friends"
Column | Type | Modifiers
--------+---------+-----------
u1 | integer |
u2 | integer |

mydb=# select * from user ;
id
----
1
2
3
4
5
6
(6 rows)

mydb=# select * from friends ;
u1 | u2
----+----
1 | 3
1 | 6
(2 rows)


假设 user.id = 1 的是A用户, 他有两个好友,id为3,6

SQL:


mydb=# select id from user, (select array_agg(u2) as friend from friends where u1 = 1) as f where not (id = any(f.friend));
id
----
1
2
4
5
(4 rows)



如果是单向好友,那么完全可以不要friends表, 把好友用array类型存储起来


mydb=# \d s_user
Table "public.s_user"
Column | Type | Modifiers
---------+-----------+-----------
id | integer |
friends | integer[] |



mydb=# select * from s_user ;
id | friends
----+---------
2 |
3 |
4 |
5 |
6 |
1 | {3,6}
(6 rows)

mydb=# select u1.id from s_user u1, s_user u2 where u2.id = 1 and not (u1.id = any(u2.friends));
id
----
2
4
5
1
(4 rows)
p8p8
2014-12-06 21:55:09 +08:00
已经搞定了,用 not in实现的。

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

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

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

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

© 2021 V2EX