简体   繁体   English

MySQL选择日期范围内每个日期不存在相关行的行

[英]MySQL select rows for which no related row exists for each date in a date range

I have a query that selects from one table based on rows in a related table not existing for a particular date. 我有一个查询,该查询根据某个特定日期不存在的相关表中的行从一个表中进行选择。 Right now, I call this query several times once with each date I'm interested in. But for performance reasons, I'd like one round trip to the database. 现在,对于每个我感兴趣的日期,我都会多次调用此查询。但是出于性能方面的考虑,我希望进行一次数据库往返。 I want to expand this query to work over a date range and return all rows in the range where there are not related rows in the other table for each date (ie UNION of results of current query for each date in range). 我想扩展此查询以在一个日期范围内工作,并返回该范围内的所有行,其中每个日期的其他表中都没有相关行(即,该范围内每个日期的当前查询结果的UNION)。 The results must include the date itself in each row. 结果必须在每一行中包含日期本身。 My current query is something like this: 我当前的查询是这样的:

   SELECT 
          t1.id,
          t1.field1,
          t1.field2, 
          '2016-03-17' AS nightof_date,
          1 as marker
        FROM 
          t1
        LEFT JOIN t2 ON (
          (t2.a_date = '2016-03-17') 
          AND (t2.t1_id=t1.id) 
          AND (some conditions...))
        WHERE 
          (t2.id is NULL)
          AND (some other conditions...)
        GROUP BY 
           t1.field3;

Here's a fiddle of a single query: http://sqlfiddle.com/#!9/553d49/6/0 这是一个查询的小提琴: http : //sqlfiddle.com/#!9/553d49/6/0

And here's what I'm trying to achieve as a result for a start date 2016-03-17 and end-date 2016-03-20: http://sqlfiddle.com/#!9/553d49/6/0 这就是我想要作为开始日期2016-03-17和结束日期2016-03-20的结果: http ://sqlfiddle.com/#!9/ 553d49/6/0

(I suppose I could programmatically generate a monster union query like this but I was hoping for something a bit more elegant where I could just use the start and end dates) (我想我可以像这样以编程方式生成一个怪物联合查询,但我希望可以使用开始日期和结束日期更优雅一些)

Is there a way to do this without using the NUMBERS or similar trick (ie. I'm hoping not to have to generate a seperate table)? 有没有一种方法可以在不使用NUMBERS或类似技巧的情况下进行操作(例如,我希望不必生成单独的表)?

Does this helps you ? 这对您有帮助吗?

SELECT 
      t1.id,
      t1.name,
      t1.birth, 
      '2015-01-01 AND 2015-01-03' AS nightof_date
    FROM 
      t1
    LEFT JOIN t2 ON (t2.t1_id=t1.id
                    AND
                    (t2.birth BETWEEN '2015-01-01' AND '2015-01-03')) 
         WHERE (t2.id is NULL)
    GROUP BY 
       t1.name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM