2015-03-02 130 views
0

合併的結果我有一個存儲的客戶像這樣的表:如何計算記錄在MySQL和PHP

id name 
-- ---- 
1  John 
2  Jane 
... 

我也有存儲客戶創建鏈接的另一個表:

id client_id link created 
-- --------- ---- ----------- 
1  1   ...  2015-02-01 
2  1   ...  2015-02-26 
3  1   ...  2015-03-01 
4  2   ...  2015-03-01 
5  2   ...  2015-03-02 
6  2   ...  2015-03-02 

我需要找到客戶今天,本月和所有時間創建了多少鏈接。我在結果中也需要他們的名字,所以我可以用一個HTML表格來顯示統計信息。我以爲我可以儘可能少這樣的代碼:

$today = $this->db->query("SELECT COUNT(*) as today, c.id as client_id, c.name FROM `links` l JOIN `clients` c ON l.client_id = c.id WHERE DATE(l.created) = CURDATE() GROUP BY c.id"); 

$this_month = $this->db->query("SELECT COUNT(*) as this_month, c.id as client_id, c.name FROM `links` l JOIN `clients` c ON l.client_id = c.id WHERE YEAR(l.created) = YEAR(NOW()) AND MONTH(l.created) = MONTH(NOW()) GROUP BY c.id"); 

$yet = $this->db->query("SELECT COUNT(*) as yet, c.id as client_id, c.name FROM `links` l JOIN `clients` c ON l.client_id = c.id WHERE GROUP BY c.id"); 

然後在PHP將它們合併爲我之前問HERE,像這樣:

$result = array_replace_recursive($today, $this_month, $yet); 

所以,我就可以循環到結果並打印我的HTML表格。

但這裏有邏輯問題。一切正常,但一個月的結果是錯誤的數字,例如,一個人創建的所有鏈接都是1,但它在月度計數器中顯示爲4!我也嘗試在SQL查詢中使用RIGHT JOIN來獲取所有客戶端,因此PHP中的array_replace_recursive可以正常工作,因爲我認爲它目前無法正常工作,但沒有成功,並且又得到了錯誤的結果。

任何人都可以告訴我一種完成工作的方法嗎?

+0

只是以供將來參考你應該添加一個SQLFiddle儘可能對數據庫的東西。真正節省時間,讓你更快得到答案。 – Jhecht 2015-03-02 07:07:51

回答

0

此查詢應該爲今天做

$query_today=" 
SELECT name, id AS user_id, (
SELECT COUNT(*) 
FROM links 
WHERE client_id = user_id AND created = '2015-03-02' 
) AS alllinks 
FROM clients" 

調整子查詢的WHERE子句個月,所有

$query_month=" 
SELECT name, id AS user_id, (
SELECT COUNT(*) 
FROM links 
WHERE client_id = user_id AND created like '2015-03%' 
) AS alllinks 
FROM clients" 

$query_all=" 
SELECT name, id AS user_id, (
SELECT COUNT(*) 
FROM links 
WHERE client_id = user_id 
) AS alllinks 
FROM clients"