【每日一题】SQL 知识大测验 | 持续更新
胜哥
作者出的题目建表的sql能提供下吗?
35题
select sum(count) as num,id from (
select count(*) count,requester_id as id from request_accepted GROUP BY requester_id
UNION
select count(*) count ,accepter_id as id from request_accepted GROUP BY accepter_id
)t
GROUP BY id
ORDER BY num desc
limit 1
33题
1.初始化:
CREATE TABLE `Orders` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`shop_id` varchar(10) COLLATE utf8mb4_bin DEFAULT NULL,
`pay_date` datetime DEFAULT NULL,
`pay_no` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
INSERT INTO `Orders`(`id`, `shop_id`, `pay_date`, `pay_no`) VALUES (1, '1001', '2020-01-11 16:43:25', 5);
INSERT INTO `Orders`(`id`, `shop_id`, `pay_date`, `pay_no`) VALUES (2, '1001', '2020-01-10 16:43:57', 3);
INSERT INTO `Orders`(`id`, `shop_id`, `pay_date`, `pay_no`) VALUES (3, '1002', '2020-01-17 16:44:09', 4);
INSERT INTO `Orders`(`id`, `shop_id`, `pay_date`, `pay_no`) VALUES (4, '1002', '2020-01-11 16:44:24', 2);
INSERT INTO `Orders`(`id`, `shop_id`, `pay_date`, `pay_no`) VALUES (5, '1002', '2020-01-11 16:44:24', 1);
INSERT INTO `Orders`(`id`, `shop_id`, `pay_date`, `pay_no`) VALUES (6, '1002', '2020-01-12 16:44:24', 0);
2.SQL
方法1:GROUP_CONCAT实现(数据库版本[5.7.16])
select * from Orders
where id in (
select SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY pay_date,pay_no),',',1) from Orders
GROUP BY shop_id
)
方法2:子查询实现(数据库版本[5.6.16])
select t.* from (
select * from Orders ORDER BY pay_date ,pay_no
)t
GROUP BY t.shop_id;
方法2有可能是不行的,不知道是数据库版本问题还是哪里设置没有
3.注意: GROUP_CONCAT有长度限制,记录过多需要注意设置以下配置 SET @@global.group_concat_max_len=数字
赞1
踩0