0

mysql 数据库中有一个表格保留,格式如下。

id | customer_id | user_id | date_booked
1  | 1           | 1       | 2012-11-5

我想获取特定用户的客户数量。所以我写了查询

select count(*), user_id, customer_id,date_booked from reservations where user_id=1 group by customer_id

这以所需的方式获取结果。但是 date_booked ,我得到了记录的第一个值。即,如果 id 为 2 的客户有 4 条记录,它将获取第一条记录的 date_booked 值。我想要最新的值,所以我改进了如下查询

select count(*), user_id, customer_id,max(date_booked) from reservations where user_id=1 group by customer_id

这将获取记录的最高日期。这仍然不是我想要获取的结果集。我想要最新的日期,但应该小于当前日期(今天)。

有没有办法像这样写条件

max(date_booked)<date(now())

我想获取最大日期但少于今天。我想在 CakePHP 中实现这一点。如果有人可以帮助查询,我可以编写 cakePHP 格式。

如有必要,请改进问题。

4

3 回答 3

1

试试这个:

select count(*), user_id, customer_id,max(date_booked) 
from reservations 
where user_id=1 
and date_booked<date(now())
group by customer_id
于 2012-11-05T09:20:13.700 回答
1
select count(*), 
       rs.user_id, 
       rs.customer_id,
       CASE WHEN max(rs.date_booked)<date(now()) then max(rs.date_booked) 
           else (select max(r.date_booked) from reservations r where r.user_id=rs.user_id 
                  and r.date_booked<date(now()) and r.customer_id=rs.customer_id
                  ) end as latestdate
from reservations rs 
where rs.user_id=1 
group by rs.customer_id
于 2012-11-05T09:27:33.010 回答
1
select  count(*),a.user_id,a.customer_id,
   IF(max(a.date_booked)>now(), b.date_booked, max(a.date_booked)) as date_booked
from reservations a left join 
   (select max(date_booked) as date_booked,customer_id 
        from reservations where date_booked < now() group by customer_id) b
on a.customer_id=b.customer_id
where a.user_id=1 
group by customer_id
于 2012-11-05T09:37:28.840 回答