使用 whereDate 从包含离今天最近的日期的行中检索数据

Retrieving data from the row containing the closest date to today with whereDate

我想在按日期筛选和分组后按价格排序。但是,因为关系不止一个,我得不到我想要的结果。

我想要的结果是得到与end_date最接近的关系的价格,并据此排序。

为此,查询、sql输出、表格和演示页面如下。 提前致谢..

demo sqlfiddle

$query->join('tableB', 'tableA.id', '=', 'tableB.pro_id')
        ->select('tableA.*', 'tableB.start_date', 'tableB.end_date', 'tableB.old_daily')
        ->where(function($sq) {
            $today = Carbon::now()->format('Y-m-d'); 
            $sq->whereDate('end_date', '>=', $today);
            })
        ->groupBy('tableA.id')
        ->orderBy('price', desc);

查询:

select `tableA`.*, `tableB`.`start_date`, `tableB`.`end_date`, `tableB`.`price` 
from `tableA` 
    inner join `tableB` on `tableA`.`id` = `tableB`.`pro_id` 
where (date(`end_date`) >= 2021-03-07) 
group by `tableA`.`id` 
order by `price` desc

表A

| id | title |
|----|-------|
|  1 |  pro1 |
|  2 |  pro2 |
|  3 |  pro3 |

表B

| id | start_date |   end_date | price | pro_id |
|----|------------|------------|-------|--------|
|  1 | 2021-06-01 | 2021-06-05 |   750 |      2 |
|  2 | 2021-05-01 | 2021-05-05 |   850 |      2 |
|  3 | 2021-04-01 | 2021-04-05 |   650 |      2 |
|  4 | 2021-06-01 | 2021-06-05 |  2750 |      1 |
|  5 | 2021-05-01 | 2021-05-05 |  2850 |      1 |
|  6 | 2021-04-01 | 2021-04-05 |  2650 |      1 |
|  7 | 2021-06-01 | 2021-06-05 |  1750 |      3 |
|  8 | 2021-05-01 | 2021-05-05 |  1850 |      3 |
|  9 | 2021-04-01 | 2021-04-05 |  1650 |      3 |

the closest to the end_date and sort it accordingly.

您应该找到给定日期和结束日期之间的差异,然后按升序排序。

ORDER BY DATEDIFF(end_date, '2021-03-07') ASC

这个查询给出了你想要的结果。 这一步使用“右连接”会是一个不错的选择。

sqlfiddle

select `tableA`.*, `tableB`.`start_date`, `tableB`.`end_date`, `tableB`.`price`
  from `tableA` 
    right join(
    SELECT id, start_date, end_date, pro_id, price, DATEDIFF(`tableB`.`end_date`, '2021-03-07') diff
    FROM `tableB`
    GROUP BY id order by diff asc
  ) `tableB` on `tableA`.`id` = `tableB`.`pro_id`
      where (date(`end_date`) >= '2021-03-07')
        group by `tableA`.`id`
          order by `price` desc