SQL 检查用户关系是否存在
我设置了一个如下所示的用户关系表。
user_relationshiplation_id
- 2
- requesting_user_idrequested_user_idrelationship_typerelationship_status
- 和
- 1
- 。
现在假设我想检查一个关系,看看两个用户之间是否存在关系,在这个例子中,ID 为 2.我可以这样做:
SELECT *
FROM user_relationship
WHERE (requesting_user_id='1' AND requested_user_id='2')
|| (requesting_user_id='2' AND requested_user_id='1')
但我想知道他们是否是更好更快的方法?
I have a user relationship table set up that looks like this.
user_relationship
- relationship_id
- requesting_user_id
- requested_user_id
- relationship_type
- relationship_status
Now say I want to check a relationship to see if it exist between two users who lets say for this example are IDs 1 & 2. I could do a:
SELECT *
FROM user_relationship
WHERE (requesting_user_id='1' AND requested_user_id='2')
|| (requesting_user_id='2' AND requested_user_id='1')
But I am wondering if their is a better faster way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
手术室的表现是出了名的差。您可以尝试使用 UNION:
UNION 将删除重复项;
UNION ALL
不会(而且速度更快)。如果有任何返回的列您不使用——它们不应该出现在查询中。
索引应该是:
...单独或单个复合索引,但您必须进行测试才能知道哪种效果最好
ORs are notoriously bad performers. You could try a UNION instead:
UNION will remove duplicates;
UNION ALL
will not (and is faster for it).If there are any columns coming back that you don't use -- they shouldn't be in the query.
Indexing should be on:
...either separately or a single composite index but you'll have to test to know which works best.
如果您假设用户无法向自己发送请求,那么这应该是等效的:
我怀疑这实际上会更快,但至少更容易阅读(在我看来)。
确保您有一个涵盖 requesting_user_id 和 requests_user_id 的索引 - 如果您经常执行此查询,那么这样的索引绝对是必需的。
If you assume that a user can not send a request to themselves, this should be equivalent:
I doubt this would actually be any faster, but it is at least easier to read (in my opinion).
Make sure you have a single index that covers both requesting_user_id and requested_user_id - if you are doing this query often, such an index is definitely a requirement.