简体   繁体   English

如何从具有匹配列的两个不同 SELECT 语句中获取行

[英]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.

相关问题 从MySQL中的每两行中选择,使用不同的列进行匹配 - select from every two rows in MySQL, using different columns for matching 如何 select 满足来自两个不同列的条件的行 - How to select rows that meet criteria from two different columns 如何从两个mysql表中选择不匹配的行 - How to select non-matching rows from two mysql table 选择两列相互引用的匹配行 - Select matching rows where two columns reference each other Select 两列中的值与请求不匹配的行 - Select rows where values in two columns not matching the request 连接两个相同的选择查询,以获取不同列中的不同行 - Joining two indentic select queries in order to get different rows in different columns 如何在MySQL的同一张表上的两个不同输入值之间的两个不同列之间选择行 - How to select rows between two different columns with two different input values on same table on mysql 如何从具有稍微不同的列的两个表中选择行? 我该如何抵消呢? - How can I select rows from two tables that have slightly different columns? How can I offset them? 如何使用两个sql表获取不匹配的列和匹配的列 - How to get none matching columns and matching columns with two sql tables 匹配来自两个不同表的两列的字符串 - Matching Strings from two columns from two different tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM