开发者

Count only unique terms based on inner SELECT JOIN

开发者 https://www.devze.com 2023-04-02 05:25 出处:网络
I\'m trying to count only unique terms as a TOTAL count. This is the original query and it works fine

I'm trying to count only unique terms as a TOTAL count.

This is the original query and it works fine

->select('DISTINCT search_tags.term AS t_name, nbr', FALSE)        
    ->from('search_tags LEFT JOIN (SELECT term AS tk, COUNT(search_tags.term) AS nbr FROM search_tags GROUP BY search_tags.term) AS TR ON search_tags.term = TR.tk ')
    ->where('search_tags.dt_added >=', '2011-08-01 09:48:54') 
    ->where('search_tags.dt_added <=', '2011-09-02 09:48:54');

// returns: [twitter,12],[facebook,6].....

The thing is that this code runs a datatable (datatable.net) so the datatable removes the select line and change it to:

SELECT COUNT(*) AS numrows
FROM (search_tags LEFT JOIN (SELECT term AS tk, COUNT(search_tags.term) AS nbr FROM search_tags     GROUP BY search_tags.term) AS TR ON search_tags.term = TR.tk)
WHERE `search_tags`.`dt_added` >= '2011-08-01 09:48:54'
AND `search_tags`.`dt_added` <= '2011-09-02 09:48:54'

// returns the same  [twitter,12],[facebook,6]..... BUT the pagination is broken.

So the datatable can count the r开发者_JS百科ows and use it as a pagination param.

But when it removes the select, it get all the rows as the DISTINCT is not there anymore.

I'm sleep deprived so I'm like stuck on try and error forever. Please help lol :P


Sorted out

->select('DISTINCT st5.term AS t_name, n_ocurrences', FALSE)        
    ->from("search_tags AS st4 
    RIGHT OUTER JOIN (SELECT DISTINCT st.term, n_ocurrences  
    FROM search_tags AS st 
    JOIN 
    (SELECT term AS n_term, COUNT(term) AS n_ocurrences 
    FROM search_tags AS st2 
    GROUP BY st2.term)
    AS st3 ON st3.n_term = st.term  
    WHERE st.dt_added >= '$min' 
    AND st.dt_added <= '$max')  AS st5 ON st5.term = 1");  

Had to add some inception selects to retrieve the right amount. Now I need to count the UNIQUE n_ocurrences under the $min, $max as the n_ocurrences is returning only the overall count.

0

精彩评论

暂无评论...
验证码 换一张
取 消