如何通过单个SQL查询检索同一数据库表中的“常用”记录?

我正在使用Ruby on Rails(版本3.2.2)和mysql2(版本0.3.11 – MySQL版本5.2.38)。 在讨论“ 如何通过关联表检索一组用户在”常见“中具有的关联对象/记录时 ”*我发现自己处于“特定”情况,我必须找到“关联对象/记录”**通过运行单个 – 出于性能原因 – 在关联数据库表上进行SQL查询。 特别是, 我想这样做只是为了检索前面提到的“关联对象/记录”,其中user_id (表示foreign key “指向” User对象) article_id (表示foreign key “指向” Article对象) ) 列值相同 (即, article_iduser_id是“common”)。

在我的案例中,我怎么能/应该检索“关联对象/记录”(可能是通过在Ruby on Rails中使用某些工具和/或SQL /数据库“方式”/“上下文”)?


*具体来说,在@Andrew Marshall发布他/她的回答之后。

** 注意 :那些“关联对象/记录”与has_many :through相关has_many :through Ruby on Rails ActiveRecord::Associations 关联问题中描述的关联 。

我认为这是一种原始的SQL方式来提取你想要的东西:

 select * from articles_users where article_id in (select articles.id from articles inner join articles_users on articles_users.article_id = articles.id where user_id = 1) and user_id = 2; 

您可以在Rails中替换用户ID的位置:

 ArticlesUser.find_by_sql(["select * from articles_users where article_id in (select articles.id from articles inner join articles_users on articles_users.article_id = articles.id where user_id = ?) and user_id = ?", @user1.id, @user2.id]) 

或者对于多个ID ::

 ArticlesUser.find_by_sql(["select * from articles_users where article_id in (select articles.id from articles inner join articles_users on articles_users.article_id = articles.id where user_id = ?) and user_id IN (?)", @user1.id, [@user2.id,@user3.id]]) 

所以从样本数据(来自您的其他问题):

 mysql> select * from articles_users; +----+---------+------------+ | id | user_id | article_id | +----+---------+------------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 1 | 3 | | 4 | 2 | 1 | | 5 | 2 | 2 | | 6 | 3 | 1 | | 7 | 3 | 3 | | 8 | 4 | 4 | +----+---------+------------+ 8 rows in set (0.00 sec) 

它将返回值:

 mysql> select * from articles_users where article_id in (select articles.id from articles inner join articles_users on articles_users.article_id = articles.id where user_id = 1) and user_id = 2; +----+---------+------------+ | id | user_id | article_id | +----+---------+------------+ | 4 | 2 | 1 | | 5 | 2 | 2 | +----+---------+------------+ 2 rows in set (0.00 sec) mysql> select * from articles_users where article_id in (select articles.id from articles inner join articles_users on articles_users.article_id = articles.id where user_id = 1) and user_id = 3; +----+---------+------------+ | id | user_id | article_id | +----+---------+------------+ | 6 | 3 | 1 | | 7 | 3 | 3 | +----+---------+------------+ 2 rows in set (0.00 sec) 

或者对于多个用户ID:

 mysql> select * from articles_users where article_id in (select articles.id from articles inner join articles_users on articles_users.article_id = articles.id where user_id = 1) and user_id in (2,3); +----+---------+------------+ | id | user_id | article_id | +----+---------+------------+ | 4 | 2 | 1 | | 5 | 2 | 2 | | 6 | 3 | 1 | | 7 | 3 | 3 | +----+---------+------------+ 4 rows in set (0.00 sec) 

你已经要求使用sql方式了 – 但是几乎可以肯定有一种方法可以做到这一点……但这应该让你开始,你可以从这里重构它。