选择具有确切字段的所有内容

Ale*_*ldi 0 mysql sql laravel eloquent

我有三个表:,document_types文档.Flows有许多属于文档类型的文档.

假设我需要选择所有具有属于特定文档类型列表的文档的流,例如,文档类型id在1,2,3和4中.换句话说,我只想选择包含文档的流以上所有文档类型ID.我应该如何使用逻辑/查询?

我的第一次尝试是,where in但它不能确保文档具有完全所有文档类型,它至少查询一个:

select * from flows where id in (
    select flow_id from documents where document_type_id in (1, 2, 3, 4)
);
Run Code Online (Sandbox Code Playgroud)

我必须用Laravel Eloquent编写我的查询,但在发现正确的逻辑之后这将是微不足道的.

Gor*_*off 6

您可以使用聚合和having:

select f.*
from flows f
where f.id in (select d.flow_id
               from documents d
               where d.document_type_id in (1, 2, 3, 4)
               group by d.flow_id
               having count(distinct d.document_type) = 4
              );
Run Code Online (Sandbox Code Playgroud)

= 4所有四种类型被发现在担保documents.请注意,我还添加了表别名和限定的所有列引用.对于您编写的任何查询,这些都是好主意.

您也可以使用相关子查询来执行此操作,这在MySQL中可能更有效:

select f.*
from flows f
where exists (select 1
              from documents d
              where d.document_type_id in (1, 2, 3, 4) and
                    d.flow_id = f.id
              having count(distinct d.document_type) = 4
             );
Run Code Online (Sandbox Code Playgroud)

特别是,这可以利用索引documents(flow_id, document_type).

  • 我在这里错过了"GROUP BY"吗?我知道大多数数据库使用`HAVING`没有`GROUP BY`工作正常我总是觉得我很难读,发现它是"hack" (2认同)