我认为这是一种提取所需内容的原始 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 方式 - 但几乎可以肯定有一种 Railsy 方式可以做到这一点......但这应该让您开始,您可以从这里重构它。