SQL加入并在表中获取计数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL加入并在表中获取计数相关的知识,希望对你有一定的参考价值。
这是我的SQL Fiddle
我现在正加入user
和address
表。现在我需要记录in_time
和out_time
填充的日志表
这是我到目前为止的SQL查询
select u.id, u.name, a.address from user u
left join address a on u.id = a.user_id
where u.id = 1
即,输出应该是这样的
id name address total_count proper_count
1 Alpha Chennai 4 3
答案
根据您的要求使用以下架构设计。 User_id必须为INTEGER,并使用datetime数据类型为in&out时间列。
CREATE TABLE log (
id BIGINT,
user_id BIGINT,
in_time datetime,
out_time datetime
);
INSERT INTO log (id,user_id, in_time, out_time) VALUES (1,1,'2018-07-21 06:50:41','2018-07-21 10:50:41');
INSERT INTO log (id,user_id, in_time, out_time) VALUES (2,1,'2018-07-22 06:50:41','2018-07-22 10:50:41');
INSERT INTO log (id,user_id, in_time) VALUES (3,1,'2018-07-23 06:50:41');
INSERT INTO log (id,user_id, in_time, out_time) VALUES (4,1,'2018-07-24 06:50:41','2018-07-22 10:50:41');
select u.id as user_id, u.name, a.address, COUNT(in_time) AS total_count, COUNT(out_time) as proper_count
from log l
INNER JOIN user u on u.id = l.user_id
INNER JOIN address a on a.user_id = u.id
GROUP BY u.id , u.name, a.address
另一答案
你可以这样:
SELECT u.id, u.name, a.address,
COUNT(*) AS total_count,
SUM(CASE WHEN l.in_time = 0 OR l.out_time = 0 THEN 0 ELSE 1 END) AS proper_count
FROM USER u
LEFT JOIN address a
ON u.id = a.user_id
LEFT JOIN log l
ON u.id = l.user_id
WHERE u.id = 1
GROUP BY u.id, u.name, a.address;
另一答案
您距离预期的查询只有一步之遥。只需要与日志表的另一个连接并使用聚合函数
select u.id, u.name, a.address,
sum(case when in_time is not null and out_time is not null
then 1 else 0 end ) as total_count ,
SUM(CASE WHEN l.in_time = 0 OR l.out_time = 0 THEN 0 ELSE 1 END) AS proper_count
from user u
left join address a on u.id = a.user_id
left join log l on u.id=l.user_id
where u.id = 1
group by u.id, u.name, a.address
http://sqlfiddle.com/#!9/b2efe0/6
id name address total_count proper_count
1 Alpha Chennai 4 3
以上是关于SQL加入并在表中获取计数的主要内容,如果未能解决你的问题,请参考以下文章