Mysql
 sql >> Database >  >> RDS >> Mysql

Come recuperare record comuni nella stessa tabella del database tramite una singola query SQL?

Questo è un modo raw-sql per tirare fuori quello che vuoi, penso:

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;

Dove puoi sostituire gli ID utente in Rails:

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])

O per più 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]])

Quindi dai dati di esempio (dalle altre tue domande):

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)

Restituirà valori in questo modo:

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)

O per più user-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)

Hai chiesto un modo sql, ma c'è quasi sicuramente un modo ingegnoso per farlo... ma questo dovrebbe farti iniziare e puoi rifattorizzarlo da qui.