Note that there are some explanatory texts on larger screens.

plurals
  1. POCounting : multiple queries or one query with multiple subqueries?
    primarykey
    data
    text
    <p>I want to make a summary script, for example, how many new users are there today, yesterday, this week, last week, this month, last month, so on.</p> <p>I'm using CodeIgniter, so I wonder which one is better? Using multiple calls on models like this :</p> <pre><code>$this-&gt;model-&gt;get_today_users(); $this-&gt;model-&gt;get_yesterday_users(); $this-&gt;model-&gt;get_this_week_users(); // so on </code></pre> <p>Each one of the functions above only return the number of users with specific date range (e.g. SELECT COUNT(*) WHERE join_date=NOW() for today_users , etc - of course using CI active record ).</p> <p>Or is it better having one single query with all necessary subqueries like this :</p> <pre><code>function stats(){ $this-&gt;db-&gt;select('*'); $this-&gt;db-&gt;select('(SELECT COUNT(*) FROM users WHERE join_date=NOW()) as today'); $this-&gt;db-&gt;select('(SELECT COUNT(*) FROM users WHERE join_date=NOW()-INTERVAL 1 DAY) as yesterday'); $this-&gt;db-&gt;select('(SELECT COUNT(*) FROM users WHERE WEEK(join_date)=WEEK(NOW()) ) as this_week'); $this-&gt;db-&gt;select('(SELECT COUNT(*) FROM users WHERE WEEK(join_date)=WEEK(NOW())-1 ) as last_week'); $this-&gt;db-&gt;select('(SELECT COUNT(*) FROM users WHERE MONTH(join_date)=MONTH(NOW()) ) as this_month'); $this-&gt;db-&gt;select('(SELECT COUNT(*) FROM users WHERE MONTH(join_date)=MONTH(NOW())-1 ) as last_month'); $this-&gt;db-&gt;from('users'); $ret = $this-&gt;db-&gt;get(); } </code></pre> <p>and then calling for example $data['stat'] = $this->model->stats(); so in views, I can call $stat->today, $stat->this_week, etc.</p> <p>Thanks in advance for the answers.</p> <p>UPDATE : What if I want to make a function that receives a date? Let's say I have to loop a month like this:</p> <pre><code>//for the sake of simplicity foreach(day in a month as $r){ $this-&gt;model-&gt;get_user_on_this_day($r); } </code></pre> <p>This means for a 30-day month, it will loop 30 times! Is there any better way than that?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload