簡體   English   中英

Active Record-CodeIgniter:3個聯接表上有多個COUNT

[英]Active Record - CodeIgniter : multiple COUNT on 3 joined tables

使用CodeIgniter和Active Record進行項目。

我遇到一個查詢問題:我的數據庫中有3個表,我不僅要聯接,還要對其中2個進行計數。 這些表分別與user_id,store_user_id,event_user_id字段鏈接

表1:用戶user_id

表2:商店store_user_id

表3:事件event_user_id

我想做的是:

1-從用戶那里獲取所有數據2-用store_user_id = user_id(可能為0)計算存儲的數量3-用event_user_id = user_id(可能為0)計算事件的數量

我已經在我的職能中做到了:

    $this->db->select('*');
    $this->db->select('COUNT(s.store_user_id) as total_store', FALSE);
    $this->db->select('COUNT(e.event_user_id) as total_event', FALSE);
    $this->db->from('user u');
    $this->db->join('store s', 's.store_user_id = u.user_id', 'left'); // this joins the user table to store table
    $this->db->join('event e', 'e.event_user_id = u.user_id', 'left'); // this joins the user table to event table  
    $this->db->group_by('u.user_id');

    $q = $this->db->get();
    if ($q->num_rows()>0){
        foreach ($q->result() as $rows) {       
            $data[] = $rows;
        }

        return $data;
    }

麻煩的是,當我在視圖中顯示total_store和total_event時,結果是相同的,並且我認為數字會在它們之間相乘。

例如:對於具有3個事件和4個商店的用戶,顯示的結果將為total_event = total_store = 12 ...

我不明白為什么,這讓我瘋狂了幾個小時! 而且,當我只計算一個數時,結果是正確的。

任何想法??

提前謝謝了 :)

最后,我實現了這個基本的SQL查詢:

$this->db->query('SELECT 
                u.*,
                x.total_store,
                y.total_event
            FROM 
            user u

            LEFT OUTER JOIN (SELECT s.store_user_id, COUNT(s.store_user_id) AS total_store
                FROM store s

                GROUP BY s.store_user_id) x ON x.store_user_id = u.user_id

            LEFT OUTER JOIN (SELECT e.event_user_id, COUNT(e.event_user_id) AS total_event  

            FROM event e

                GROUP BY e.event_user_id) y ON y.event_user_id = u.user_id
        ');

希望對別人有幫助

當您count()時,您是在計算行數,而不是結果集中不同值的數目。 沒錯,這個數字正好相乘:結果集中每個用戶-商店-事件組合都有一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM