0

编辑为了进一步简化这一点。

我们来看看这个结构:

表 1:idProduct (int) | 名称(varchar)

表 2:idDay (int) | idProduct (int) | 日期开始(日期时间) | date_end(日期时间)

idProduct 是两个表中的公共列。表二包含与此类似的数据:

0, 2, 11/22/2012, 11/22/2012
1, 2, 11/23/2012, 11/23/2012
2, 2, 11/24/2012, 11/24/2012
3, 2, 00/00/0000, 11/25/2012
4, 2, 11/25/2012, 00/00/0000

请注意,date_start、date_end 或两者都可能全为零,在这种情况下,此上限或下限被视为不受限制/不受限制。

在上述情况下,我只想选择 ID 为 2 的 idProduct,前提是今天的日期介于时间段之间 - date_start 中的最早日期和 date_end 中的最晚日期。如果 date_start 是 00/00/0000 总是返回产品但是如果 date_end 在未来。相反适用于 date_end 全为零并且 date_start 被设置。如果两列都为零,则返回产品。

4

2 回答 2

1

我在您的问题中没有看到“LEFT JOIN”要求:就在您的标题中。所以

SELECT t1.idProduct, t1.Name
FROM table1 t1
INNER JOIN table2 t2 ON t1.idProduct = t2.idProduct
WHERE DATE(t2.date_start) < DATE(NOW())--this will also take values with DATETIME = 0000
AND (DATE(t2.date_end) > DATE(NOW()) OR YEAR(t2.date_end) = 0)
GROUP BY t1.idProduct, t1.Name

或者如果您想检查产品是否至少有一个 start_date 小于今天(或 0)和至少一个 end_date 大于今天(或 0),即使 start_date 和 end_date 不共享相同的 idDay :

SELECT t1.idProduct, t1.Name
FROM table1 t1
WHERE t1.idProduct IN
    (SELECT t2.IdProduct
    FROM table t2
    GROUP BY t2.IdProduct
    HAVING 
    MIN(t2.date_start) <= DATE(NOW()) AND 
    (MAX(t2.date_end) >= DATE(NOW()) OR YEAR(MAX(t2.date_end)) = 0))

这将需要:

最小开始日期 = 0 和最大结束日期 = 0

min start_date = 0 和 max end_date >= 今天

min start_date <= 今天和 max end_date =0

min start_date <= 今天和 max end_date >= 今天

于 2012-06-27T08:12:50.960 回答
0
select
  t1.idproduct,
  t1.name
from table as t1
  left join table2 as t2
    on t1.idproduct = t2.idproduct
where date(date_start) < date(now())
    and date(date_end) > date(now())

已编辑

select
  t1.idproduct,
  t2.idproduct,
  t2.name
from table as t1
  left join (select
               max(idproduct),
               name
             from table2
             where date(date_start) < date(now())
                 and date(date_end) > date(now())) as t2
    on t1.idproduct = t2.idproduct

当然,它不会选择结束日期为 00:00:00 的那些记录

于 2012-06-27T08:10:14.300 回答