如何在一个读取语句中读取 mySQL table 中的多个字符串和日期?

How to read multiple strings and dates in mySQL table in one read statement?

我有一个 mySQL table 类似于以下示例:

DOC_OwnerID   DOC_type    DOC_start_date    DOC_end_date   
100            JANUARY     1/1/2017          12/31/2018
100            JANUARY     1/1/2018          12/31/2019
100            DRIVER      1/5/2018          1/4/2019 
100            LICENSE     2/5/2015          2/5/2016
100            LICENSE     4/5/2018          2/5/2019
200            JANUARY     1/2/2017          1/2/2018
200            DRIVER      1/2/2018          1/2/2019  

在我的应用程序逻辑中,我需要找到任何所有者 (DOC_OwnerID) 在给定时间段内拥有三个基本强制性文件(JANUARY、DRIVER、LICENSE)。必须计数 3 才能表明所有者拥有三个文件。 (每个时间段的文档名称是唯一的)

例如:OwnerID = 100,日期 = 4/9/2018

true =>     100            JANUARY     1/1/2018          12/31/2019
true =>     100            DRIVER      1/5/2018          1/4/2019 
true =>     100            LICENSE     4/5/2018          2/5/2019

应该return 3 显示所有三个文件在给定日期内均有效。我可以使用 COUNT 但我如何 select 记录因为 DPC_Type 不是唯一的。

但是 owner = 200 永远不会成立,因为他没有记录 LICENSE。

我可以在我的应用程序中通过读取所有者的所有记录来做到这一点。我怎样才能在 sql 中立即执行此操作?

谢谢, 普布度

您可以使用聚合:

SELECT DOC_OwnerID
FROM mytable
WHERE  @mydate >= DOC_start_date AND @mydate <= DOC_end_date
GROUP BY DOC_OwnerID
HAVING
    MAX(DOC_type = 'JANUARY') = 1
    AND MAX(DOC_type = 'DRIVER') = 1
    AND MAX(DOC_type = 'LICENSE') = 1

对于给定的 @mydate 参数,这将 return DOC_OwnerID 具有所有三个 DOC_type 值。

您想要 return 来自 table 的所有有效行,对吧?
所以必须把得到满足条件的doc_owner_id后的结果加入到table:

select t.* 
from tablename t inner join (
  select doc_owner_id 
  from tablename
  where 
    str_to_date('4/9/2018', '%m/%d/%Y') between doc_start_date and doc_end_date
    and
    doc_type in ('JANUARY', 'DRIVER', 'LICENCE')
  group by doc_owner_id
  having count(distinct doc_type) = 3
) g on g.doc_owner_id = t.doc_owner_id
where
  str_to_date('4/9/2018', '%m/%d/%Y') between t.doc_start_date and t.doc_end_date
  and
  t.doc_type in ('JANUARY', 'DRIVER', 'LICENCE')