sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo recuperar registros comunes en la misma tabla de base de datos a través de una sola consulta SQL?

Esta es una forma de raw-sql para sacar lo que quieres, creo:

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;

Donde puede sustituir las identificaciones de usuario en 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 para múltiples identificaciones::

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

Entonces, a partir de datos de muestra (de sus otras preguntas):

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)

Devolverá valores así:

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 para múltiples identificaciones de usuario:

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)

Ha solicitado una forma de sql, pero es casi seguro que hay una forma sencilla de hacer esto... pero esto debería ayudarlo a comenzar, y puede refactorizarlo desde aquí.