我的数据库中有以下表格。我只列出了可用于加入的重要列。
目前,我对每个 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
;
由于需要列出超过1,000种产品,我想将它们合并为一个查询。我该怎么做?
答案 0 :(得分: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
对于将来,如果您可以将代码粘贴为代码而不是图像,那将是非常棒的。人们无法简单地复制代码的粘贴片段,并且必须再次键入所有内容...
答案 1 :(得分:0)
尝试加入两个查询
SELECT * FROM (
(First Query) as assigned_licn
INNER JOIN
(Second Query) as total_licn
USING (id)
);