SQL构造双向图

编程入门 行业动态 更新时间:2024-10-18 06:14:17
本文介绍了SQL构造双向图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想要一个具有以下列的表:id,user_id1和user_id2.

I want to have a table with columns: id, user_id1, and user_id2.

基本上,这将表示一个朋友图,其链接表示user1是user2的朋友,反之亦然.

basically this will resprsent a friend graph with the link representing that user1 is friends with user2 AND vice versa.

我的设置得到一个用户,然后是他们的朋友列表.鉴于我不想在表中有多余的条目,应该如何处理呢?

my setup gets a single user and then a list of their friends. given that I don't want to have extra entries in my table how shoudl I handle this?

我想做类似的事情:insert into friendship (user_id1, user_id2) values (<id1>, <id2>) where ...

但是我不确定如何执行SQL中的条件逻辑

but I'm not sure how to do conditional logic like that in SQL

推荐答案

您可以通过CHECK约束强制user_id1始终小于user_id2:

You could force user_id1 to always be less than user_id2 with a CHECK constraint:

CHECK (user_id1 < user_id2)

大概不允许人们成为自己的朋友.然后在插入之前确保ID顺序正确.提取朋友列表时,您仍然需要检查两列:

Presumably people aren't allowed to be their own friends. And then make sure the IDs are in the right order before you INSERT. When extracting a list of friends, you'd still have to check both columns though:

select user_id2 from friendship where user_id1 = X union all select user_id1 from friendship where user_id2 = X

X当然是您感兴趣的人.要查看两个人是否是朋友,只需按正确的顺序排列其ID,然后选择SELECT.

where X is, of course, the person you're interested in. And to see if two people are friends, just arrange their IDs in the right order and SELECT away.

更多推荐

SQL构造双向图

本文发布于:2023-10-24 20:10:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:双向   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!