2017-06-03 132 views
0


我在我的數據庫中有以下表格。我只列出了可用於連接的重要列。
MySQL連接表與COUNT值

enter image description here

我需要得到下面的輸出
enter image description here

目前我使用兩個單獨的查詢每個COUNT

對於分配的許可證

select 
    products.id,products.name,COUNT(assigned_licenses.id) 
from 
    deployment_users 
inner join 
    assigned_licenses 
on 
    deployment_users.id = assigned_licenses.deployment_user_id 
inner join 
    products 
on 
    assigned_licenses.id = products.id 
and 
    deployment_users.customer_id = 10 
group by 
    assigned_licenses.id 
; 

對於許可證總數

select 
    products.id,products.name,COUNT(total_licenses.id) 
from 
    customers 
inner join 
    total_licenses 
on 
    customers.iccode = licenses.iccode 
inner join 
    products 
on 
    total_licenses.id = products.id 
and 
    customers.id = 10 
group by 
    total_licenses.id 
; 

由於有比需要列出一個1000多的產品,我想將它們合併成一個單一query.How我能做到這一點?

回答

1

你的規範留下了一些解釋的餘地​​(例如,可以將用戶已經分配的許可證沒有許可證總數?如果是我的查詢將會失敗。),但我會用這個去。

SELECT 
    products.id, 
    products.name, 
    Count(Distinct total_licenses.id) As CountTotalLicenses, 
    Count(Distinct assigned_liceses.deployment_users_id) As CountAssignedLicenses 
FROM products 
    LEFT JOIN total_licenses ON total_licenses.products_id = products.id 
    LEFT JOIN customers ON customers.iccode = total_licenses.customers_iccode 
    LEFT JOIN assigned_licenses ON assigned_liceses.total_licenses_id = total_licenses.id 
WHERE 
    customers.id = 10 
GROUP BY 
    products.id, 
    products.name 

對於未來,如果您可以將代碼作爲代碼粘貼而不是圖像,那將是非常棒的。人們不能簡單地複製代碼的粘貼片段,並且必須再次輸入所有內容...

+0

很酷。你根本沒有使用'deployment_users'。你能解釋一下這個查詢背後的想法嗎? – Pradeep

+0

嗯,思考嗯:) – chickahoona

+0

如果你的意思是「它是如何工作」,訣竅是在這些「計數(獨特...)」表達式與羣組。如果你有5行的列X與值(5,2,4,2,1),那麼它將返回4.對於值(3,3,5,5)它將返回2.所以它會檢查如何存在許多「獨特」的價值,並計數這些價值。這有助於你理解它嗎? – chickahoona

0

試着加入這兩個查詢的

SELECT * FROM (
    (First Query) as assigned_licn 
    INNER JOIN 
    (Second Query) as total_licn 
    USING (id) 
);