如何在单个查询中使用不同的user_id获取计数,类型和日期

时间:2016-02-09 08:07:17

标签: php mysql

我在MySQL中创建了一个表。它由以下数据组成:

user_pack

id    type     from         to         user_id   current_plan  created_ at   
  1    trail  01-01-2016  05-01-2016   1              0          01-01-2016
  2    free   06-01-2016  10-01-2016   1              0          06-01-2016
  3    main   11-01-2016  20-01-2016   1              1          11-01-2016
  4    main   21-01-2016  29-02-2016   1              1          21-01-2016
  5    trail  01-01-2016  29-02-2016   2              1          01-01-2016
  6    trail  01-01-2016  05-01-2016   3              0          01-01-2016
  7    free   06-01-2016  29-02-2016   3              1          06-01-2016
user_id= 1 =>first register for type=trail it started from = 01-01-2016  to=05-01-2016.in that time current_plan=1 after expired current_plan=0.
           =>second register for type=free it started from = 06-01-2016  to=10-01-2016 in that time current_plan=1 after expired current_plan=0.
           =>third register for type=main it started from = 11-01-2016  to=20-01-2016 in that time current_plan=1 after expired current_plan=1 only
           =>fourth register for type=main it started from = 21-01-2016  29-02-2016 and now it in activation current plan=1.

当我在两个日期01-01-201621-01-2016之间搜索created_atcurrent时,计划必须为1,今天日期必须介于两者之间从表格到目前为止。

我希望以这种方式输出结果:

array0=>['trail count'=>1,'free count'=>0,'main count'=>0,'date'=>01-01-2016]
array1=>['trail count'=>0,'free count'=>1,'main count'=>0,'date'=>06-01-2016]
array2=>['trail count'=>0,'free count'=>0,'main count'=>0,'date'=>11-01-2016]
array3=>['trail count'=>0,'free count'=>0,'main count'=>1,'date'=>21-01-2016]

1 个答案:

答案 0 :(得分:1)

为了能够执行此类查询,您应该考虑将表拆分为3个不同的表:

<强> pack_type:

  • ID

<强> pack_event:

  • ID
  • pack_type_id

<强> pack_registration:

  • ID
  • pack_event_id
  • USER_ID
  • current_plan
  • created_at

此结构将阻止冗余,并使您能够进行复杂的查询。对date_seancefromto使用日期列也很重要。

使用此表结构,您将能够使用以下查询查询给定时间段和created_at的所有用户注册:

current_plan=1