sql - 如何同时进行两个计数查询?
问题描述
表结构:
CREATE TABLE followers (
user_id int not null REFERENCES users(id) on DELETE CASCADE,
following int not null REFERENCES users(id) on DELETE CASCADE,
PRIMARY key (user_id, following)
);
从这里我想获取关注者和关注者的数量。目前我正在这样做:
-- user 1 following
SELECT count(*) from followers f
WHERE f.user_id = 1;
-- user 1 followers
SELECT count(*) from followers f
WHERE f.following = 1;
有什么方法可以将其作为单个查询来执行吗?
期望的输出:
~~~~~~~~~~~~~~~~~~~~~~~
| followers | following |
~~~~~~~~~~~~~~~~~~~~~~~
| 2 | 1 |
~~~~~~~~~~~~~~~~~~~~~~~
解决方案
您可以在 COUNT() 中使用FILTER :
SELECT
COUNT(*) FILTER(WHERE user_id = 1) AS followers
, COUNT(*) FILTER(WHERE following = 1) AS following
FROM followers
WHERE user_id = 1
OR following = 1;
推荐阅读
- javascript - 如何为 PHP 生成的表使用 JQuery 的 .click 函数
- .net-core - 是否可以根据请求参数注入作用域依赖项?
- python - 在列中添加值
- azure - Azure & Centos 7 & Centos 我尝试设置邮件服务,但 rDNS/PTR 检查 IP 10.0.0.4 = 未找到
- unity3d - Unity WebGL - 在本地主机上工作但不在服务器上
- android - 无法在 androidx.appcompat.app.ActionBarDrawerToggle 中使用操作栏
- sql - 如何根据两个条件从 MS Access 中的多个表中找出重复记录
- php - Symfony 3.4 路由在新安装中不起作用
- java - 调整浮动 ViewGroup 的大小和移动
- oracle - 在 PL/SQL 中将 & 转换为 &