拼接
table_1:
1 a,b,c
2 a,b
table_2:
a 北京
b 上海
c 南京
输出
1 北京,上海,南京
CREATE TABLE `table_1` (
`id` int DEFAULT NULL,
`daihao` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `table_2` (
`daihao` varchar(100) DEFAULT NULL,
`city` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SELECT
id,
GROUP_CONCAT(city)
FROM
(
SELECT
id,
daihao,
SUBSTRING_INDEX(SUBSTRING_INDEX(a1.daihao,',',a2.help_topic_id + 1),',' , -1) as fenjie
FROM table_1 as a1
INNER JOIN mysql.help_topic as a2
on a2.help_topic_id < LENGTH(a1.daihao) - LENGTH(REPLACE(a1.daihao,',','')) + 1
) as tmp1
INNER JOIN table_2
on tmp1.fenjie = table_2.daihao
GROUP BY id
1 北京,上海,南京
2 北京,上海
解释一下:
首先使用mysql中一个自带的有递增的表,通过join将 a,b,c 变成
a,b,c 0
a,b,c 1
a,b,c 2
之后通过substring_index 对数据分割
substring_index 通过分隔符和值来确定取第几个分隔符之前的。
比如
1,就是 a
2,就是 a,b
再通过-1,取最后的,就将分割的数依次取了出来(没有分隔符就是取的原字符)
这样就变成了
a,b,c 0 a
a,b,c 0 b
a,b,c 0 c
再inner join 第二张表拿到city
通过group_concat()对字符进行拼接
table_1:
a 1
b 1
c 1
a 2
c 2
a 3
b 3
输出连续登陆天数
CREATE TABLE `user_profile` (
`id` int NOT NULL,
`install_date` date DEFAULT NULL,
`active_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
SELECT
id,
active_date - rank_ as diff,
count(1) as a
FROM (
SELECT
id,
ROW_NUMBER() over(partition by id order by active_date) as rank_,
active_date
from user_profile
) as t1
GROUP BY id, diff
having a >= 2
这题通过排序,如果是连续登陆,那么相减后的值是相同的,所以可以拿来作为判定条件。
标签:面试题,DEFAULT,mysql,date,table,NULL,daihao,id From: https://www.cnblogs.com/yych0745/p/16831562.html