mysql 基础不牢,请教各位 v 友一个查询语句。

2022-01-05 10:54:16 +08:00
 fragrans23

1.数据表有两个字段 bus_id 和 record_id ,record_id 唯一不重复,bus_id 可以对应多个 record_id 。现求 record_id 的数量,多个 bus_id 对应的 recordId 算一个数量。 2.不能直接求去重后 bus_id 的数量,其他业务可能没有 bus_id

2590 次点击
所在节点    程序员
17 条回复
cwcc
2022-01-05 10:59:09 +08:00
1 我没太懂,record_id 都唯一不重复了,直接 count 应该就好?(或者你把唯一不重复的这个字段没设置成 primary ?那就不行)

终极解决:3NF
Xusually
2022-01-05 11:01:04 +08:00
最简单的 COUNT 满足不了么?还是我没理解需求?
sunhelter
2022-01-05 11:01:18 +08:00
不能直接去重就分别 union 咯

SQL Server 可以这么写:
select SUM(ct)
select COUNT(1) ct from table where ISNULL(bus_id,'')!='' group by bus_id
union all
select COUNT(1) from table where ISNULL(bus_id,'')=''
sunhelter
2022-01-05 11:02:11 +08:00
上面的 SQL 在 SUM(ct)后加个括号,到结尾加反括号
fragrans23
2022-01-05 12:00:38 +08:00
@crazywhalecc 但是,如果一个 bus_id 对应多个 record_id,这种情况计数 record_id 只记一个,例如一个 bus_id 对应两个 record_id,count(record_id)时,只记一次。直接 count 会记录两次吧
zheng96
2022-01-05 12:23:57 +08:00
前提是 bus_id 和 record_id 本身不会重复,如果会重复可以在 then 后头拼接个前缀区分下
select count(
distinct(
case
when record_id is null then null
when bus_id is null then record_id
else bus_id end
)
) from table;
fragrans23
2022-01-05 12:52:02 +08:00
@Xusually 要考虑 bus_id 对应多个 record_id 的情况,对应多个的话,record_id 只记录一次
fragrans23
2022-01-05 13:04:23 +08:00
@zheng96 谢谢大佬,貌似可以,我得多试一下
fragrans23
2022-01-05 13:09:21 +08:00
@sunhelter 感谢回复,mysql 好像不行
themostlazyman
2022-01-05 13:34:49 +08:00
问题描述没太懂,建议给一个最小化的表结构,再加几条典型数据来说明你的问题。
xiangyuecn
2022-01-05 13:43:40 +08:00
“不能直接求去重后 bus_id 的数量,其他业务可能没有 bus_id”

分两条简单的 sql 语句搞定,没必要写一条蹩脚的 sql
JKeita
2022-01-05 13:59:50 +08:00
同没看懂题目
newtype0092
2022-01-05 14:10:45 +08:00
(select count(*) from table where bus_id is null) + (select count(*) from table where bus_is is not null group by bus_id)
zhuangjia
2022-01-05 14:11:55 +08:00
题目中的描述部分 “多个 bus_id 对应的 recordId 算一个数量” 有歧义,楼主在 #7 给了补充描述:“bus_id 对应的 多个 recordId 算一个数量”。
ray5173
2022-01-05 14:15:04 +08:00
select count(distinct a.record_id)
from a
left join b on a.record_id = b.bus_id
where b.bus_id is not null
zhuangjia
2022-01-05 14:15:15 +08:00
@fragrans23

//最小化表结构:
CREATE TABLE `bus_test` (
`record_id` int(11) NOT NULL AUTO_INCREMENT,
`bus_id` int(11) DEFAULT '0',
PRIMARY KEY (`record_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

//测试数据
INSERT INTO `test`.`bus_test` (`bus_id`) VALUES (FLOOR(RAND() * 10));

//查询 SQL
select sum(case when t.bus_id is null then t.record_count else 1 end) from (SELECT count(record_id) as record_count,bus_id FROM `bus_test` group by bus_id) t;
fragrans23
2022-01-05 16:08:08 +08:00
@zhuangjia 感谢回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/826277

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX