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

SQL para devolver un conjunto combinado de resultados

Esto se puede lograr con división relacional :

select r.order_id from (
  select 
    dividend.*  
  from your_table_or_query as dividend  -- assumes no duplicates in `dividend`; use `distinct` if there are any
  inner join divisor
  on dividend.value = divisor.value
) as r
group by r.order_id
having count(*) = (select count(*) from divisor);

resultado:

+----------+
| order_id |
+----------+
|     1236 |
|     1239 |
+----------+
2 rows in set (0.00 sec)

donde su consulta es your_table_or_query y

select 260 as value from dual union select 264 as value from dual

es divisor .

Esto devolverá los ID de pedido 1236 y 1239; entonces pueden ser join editado a la consulta original para obtener todas las filas con esos ID de pedido si eso es lo que desea.

Consulta completa junto con declaraciones de inserción:

create table divisor (value int);
insert into divisor values (260), (264);

create table your_table_or_query (value int, order_id int);
insert into your_table_or_query values (260, 1234), (260, 1235), (260, 1236), (264, 1236), (260, 1237), (260, 1238), (260, 1239), (264, 1239), (264, 1240), (260, 1241);


select y.* from (
  select r.order_id from (
    select
      dividend.*
    from your_table_or_query as dividend
    inner join divisor
      on dividend.value = divisor.value
  ) as r 
  group by r.order_id
  having count(*) = (select count(*) from divisor)
) as quotient
inner join your_table_or_query y
  on quotient.order_id = y.order_id;

Resultado:

+-------+----------+
| value | order_id |
+-------+----------+
|   260 |     1236 |
|   264 |     1236 |
|   260 |     1239 |
|   264 |     1239 |
+-------+----------+
4 rows in set (0.00 sec)