简体   繁体   English

SQL根据两列查找记录

[英]SQL find records based on two columns

Given a users table with primary key of id , I have a foreign table called friends which only has two fields ( userid1, userid2 ). 给定一个主表为id的用户表,我有一个名为friends userid1, userid2该表只有两个字段( userid1, userid2 )。 This allows us to create any kind of relationship between different users (one to many, one to one, etc). 这使我们可以在不同用户之间创建任何类型的关系(一对多,一对一等)。 A user can appear in either column and both columns are equal. 用户可以出现在任一列中,并且两列相等。 IOW, a single entry per relationship. IOW,每个关系一个条目。

How can I pull all of the friends that a given user id has. 如何提取给定用户id所有朋友。 Say Jonny, has 3 friends and his user id is 16 ... should my sql query look like this? 说乔尼(Jonny),有3个朋友,他的用户id16 ...我的SQL查询应该像这样吗?

SELECT * 
FROM   db.users 
       JOIN db.friends 
         ON db.users.id = db.friends.userid1 
            AND db.users.id = 16 

Hopefully, this is clear. 希望这很清楚。 Also, if possible, can I exclude Jonny from the result set? 另外,如果可能,我可以从结果集中排除Jonny吗?

This query, as listed gies me the following: 列出的该查询使我了解以下内容:

id      name    uuid                       birthday        userid1  userid2
16  jonny   ABCDEFGHIJKLMNOP    1967-04-27 01:00:00     1         2
16  jonny   ABCDEFGHIJKLMNOP    1967-04-27 01:00:00     1         3

This is pretty close, except I want his friends, not jonny 这很接近,除了我要他的朋友,而不是乔尼


Thanks guys, so I got it to work thanks to you. 谢谢大家,所以我感谢您。 Here is the final working query. 这是最终的工作查询。

SELECT * 
FROM db.users
WHERE db.users.id IN
(
  SELECT db.friends.userid2 as id FROM db.friends WHERE db.friends.userid1 = 16
    union
  SELECT db.friends.userid1 as id FROM db.friends WHERE db.friends.userid2 = 16
)

which gives me: 这给了我:

id      name    uuid                       birthday 
2   robin   ABCDEFGHIJKLMNOP    1967-04-27 01:00:00
3   gary    ABCDEFGHIJKLMNOP    1967-04-27 01:00:00

Add the condition for the user.id to your where clause at the end: 最后将user.id的条件添加到where子句中:

Select * From users
INNER JOIN friends on
users.id = friends.userid1
Where users.id = 16

Also, I would use an Inner Join which will return all records from users only where there is a match in friends 另外,我将使用Inner Join ,仅当friends中有匹配项时,才会从users返回所有记录

You could do a sub query like: 您可以执行以下子查询:

SELECT * 
FROM users
WHERE id IN
(
  SELECT userid2 as id FROM db.friends WHERE userid1 = 16
)

You should filter on the friends table, not the users table. 您应该过滤好友表,而不是用户表。

SELECT friends.*
FROM friends
INNER JOIN users
  ON friends.userid2 = users.id
WHERE friends.userid1 = 16

If you just need the friend ID's then there is not reason to join at all 如果您只需要朋友ID,那么根本没有理由加入

SELECT userid2
FROM friends
WHERE userid1 = 16

您需要一个朋友ID列表:

SELECT U FROM DB.USERS U WHERE U.ID IN ( SELECT F.USERID2 FROM DB.FRIENDS F WHERE F.USERID1 = 16)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM