来自连接表的SQL计数 [英] SQL Count from joined table
问题描述
我有一个表'lijsten',一个表'werknemerlijsten'和一个表'categorieen'。现在我使用查询来获得计数
SELECT id,naam,beschrijving,count(wl.werknemer_id)as aantal
FROM lijsten l
LEFT JOIN werknemerlijsten wl
ON l.id = wl.lijst_id
GROUP BY l.naam
ORDER BY naam
但是,当我用另一个计数器从另一个表中尝试相同的查询时,结果为false。
SELECT l.id,l.naam,beschrijving,count(c.lijst_id)as aantal_cat,count(wl.lijst_id)as aantal_lijst
FROM lijsten l
LEFT JOIN werknemerlijsten wl ON l。 id = wl.lijst_id
LEFT JOIN categorieen c ON l.id = c.lijst_id
GROUP BY l.naam
ORDER BY naam
任何想法我可能做错了什么?谢谢
您的左连接
s引入了具有多个匹配给定的ID。修复计数的快捷方法是使用 count(distinct)
而不是 count()
:
SELECT a.id,l.naam,beschrijving,
count(distinct c.lijst_id)as aantal_cat,count(distinct wl .lijst_id)as aantal_lijst
FROM lijsten l
LEFT JOIN werknemerlijsten wl ON l.id = wl.lijst_id
LEFT JOIN categorieen c ON l.id = c.lijst_id
GROUP BY l.naam
ORDER BY naam;
另一种方法是在连接之前聚合表格,在子查询中进行计数。 p>
I have a table 'lijsten', a table 'werknemerlijsten' and a table 'categorieen'.
Now i'm using the Query to get the count
SELECT id, naam, beschrijving, count(wl.werknemer_id) as aantal
FROM lijsten l
LEFT JOIN werknemerlijsten wl
ON l.id = wl.lijst_id
GROUP BY l.naam
ORDER BY naam
But when i try the same query with another count, from another table, the results are false.
SELECT l.id, l.naam, beschrijving, count(c.lijst_id) as aantal_cat, count(wl.lijst_id) as aantal_lijst
FROM lijsten l
LEFT JOIN werknemerlijsten wl ON l.id = wl.lijst_id
LEFT JOIN categorieen c ON l.id = c.lijst_id
GROUP BY l.naam
ORDER BY naam
Any idea what i might be doing wrong? Thanks
Your left join
s are bringing in tables that have multiple matches for a given id. The quick and easy way to fix counts is to use count(distinct)
instead of count()
:
SELECT l.id, l.naam, beschrijving,
count(distinct c.lijst_id) as aantal_cat, count(distinct wl.lijst_id) as aantal_lijst
FROM lijsten l
LEFT JOIN werknemerlijsten wl ON l.id = wl.lijst_id
LEFT JOIN categorieen c ON l.id = c.lijst_id
GROUP BY l.naam
ORDER BY naam;
An alternative approach is to aggregate the tables before the join, doing the counts in the subquery.
这篇关于来自连接表的SQL计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!