[英]How to get rows from two different SELECT statements with matching columns
I have a table called relationships in my MySQL database which has the columns follower_id and followed_id.我的 MySQL 数据库中有一个名为关系的表,其中包含 follower_id 和 follow_id 列。 These represent followings on Instagram, for example if an account with ID 1 followed an account with ID 2 then a row would exist in my table where follower_id was 1 and followed_id was 2.
这些代表 Instagram 上的关注者,例如,如果 ID 为 1 的帐户关注 ID 为 2 的帐户,那么我的表中将存在一行,其中 follower_id 为 1,followed_id 为 2。
What I want to do is be able to find accounts that follow both account with ID 1 AND account with ID 4 for example.例如,我想要做的是能够找到同时关注 ID 为 1 的帐户和 ID 为 4 的帐户的帐户。 I have tried creating temporary tables using SELECT statements like this:
我曾尝试使用这样的 SELECT 语句创建临时表:
CREATE TEMPORARY TABLE temp1
SELECT follower_id FROM relationships
WHERE followed_id = '1'
and和
CREATE TEMPORARY TABLE temp2
SELECT follower_id FROM relationships
WHERE followed_id = '4'
and trying to cross reference the two temporary tables but this takes a very long time.并尝试交叉引用两个临时表,但这需要很长时间。 Is there a quicker way to do this in MySQL?
在 MySQL 中有没有更快的方法来做到这一点?
Simply you can select distinct follower_id using below query:-只需使用以下查询,您就可以选择不同的 follower_id:-
SELECT DISTINCT follower_id FROM relationships
WHERE followed_id IN ('1', '4');
Hope, this will solve your problem.希望,这将解决您的问题。
SELECT follower_id FROM relationships WHERE followed_id=1 AND follower_id IN
(SELECT follower_id FROM relationships WHERE followed_id=4)
A pretty simple method is:一个非常简单的方法是:
SELECT follower_id
FROM relationships
WHERE followed_id IN (1, 4)
GROUP BY follower_id
HAVING COUNT(*) = 2; -- number of followed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.