[英]Trying to count the number of occurences that 3 columns from 2 tables have on my organizations table? I need the occurrences joined in one table
-- 2. In one table, show how many private topics, admins, and standard users each organization has.
SELECT organizations.name, COUNT(topics.privacy) AS private_topic, COUNT(users.type) AS user_admin, COUNT(users.type) AS user_standard
FROM organizations
LEFT JOIN topics
ON organizations.id=topics.org_id
AND topics.privacy='private'
LEFT JOIN users
ON users.org_id=organizations.id
AND users.type='admin'
LEFT JOIN users
ON users.org_id=organizations.id
AND users.type='standard'
GROUP BY organizations.name
;
org_id is the foreign key that reals both the users table and topics table. org_id 是实现用户表和主题表的外键。 It keeps giving me the wrong result by only either counting the number of admins or standard users and putting that for all rows in the each column.
它只通过计算管理员或标准用户的数量并将其放入每列中的所有行来不断给我错误的结果。 Any help is really appreciated as I have been stuck on this for a while now!
任何帮助都非常感谢,因为我已经坚持了一段时间了!
So, I am getting an error when I do as you said which is that the users table cannot be specified more than once.所以,当我按照你说的那样做时,我收到一个错误,即不能多次指定用户表。 I updated the code to how you said to write it but still nothing.
我将代码更新为您所说的编写方式,但仍然没有。 They really don't give me any sample data either but I just made some queries and saw the number of times there are private topics for example, which is in the privacy column of the topics table.
他们也确实没有给我任何示例数据,但我只是进行了一些查询,并看到了私人主题的次数,例如,在主题表的隐私列中。 When I dont get this error as I said, the joins seem to overwrite themselves where each row for all the columns is the same as the last join.
当我没有像我说的那样收到这个错误时,连接似乎会覆盖自己,其中所有列的每一行都与最后一个连接相同。
It appears to me that topics and users have no relationship.在我看来,主题和用户没有关系。 You're just trying to get the result together in a single query.
您只是想在单个查询中获得结果。 There are other and possibly better ways to accomplish that but I think this will fix what you've got already (assuming you have id columns for each table.)
还有其他可能更好的方法来实现这一点,但我认为这将解决您已经拥有的问题(假设每个表都有 id 列。)
SELECT
organizations.name,
COUNT(DISTINCT topics.id) AS private_topic,
COUNT(DISTINCT users.id) FILTER (WHERE users.type = 'admin') AS user_admin,
COUNT(DISTINCT users.id) FILTER (WHERE users.type = 'standard') AS user_standard`
FROM organizations
LEFT JOIN topics
ON organizations.id = topics.org_id AND topics.privacy = 'private'
LEFT JOIN users
ON users.org_id = organizations.id
GROUP BY organizations.name;
I propose this as a more straightforward way:我建议这是一种更直接的方式:
SELECT
min(o.name) as "name",
(
select count(*) from topics t
where t.org_id = o.id AND t.privacy = 'private'
) as private_topics,
(
select count(*) from users u
where u.org_id = o.id and u.type = 'admin'
) AS user_admin,
(
select count(*) from users u
where u.org_id = o.id and u.type = 'standard'
) AS user_standard
FROM organizations o
GROUP BY o.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.