sql-高级字符串函数 / 正则表达式 / 子句
select user_id, concat(upper(left(name,1)),lower(right(name,length(name)-1))) as name from Users order by user_id
left(name, 1)
-
作用:取出
name字符串的第一个字符 -
例如:
'alice'→'a'
2. upper(left(name,1))
-
作用:将第一个字符转成大写
-
例如:
'a'→'A'
3. length(name)-1
-
作用:计算除第一个字符以外的剩余字符数
-
例如:
'alice'→5 - 1 = 4
4. right(name, length(name)-1)
-
作用:从字符串的右侧取出剩余的字符
-
例如:
'alice'→'lice'
5. lower(...)
-
作用:将剩余的字符全部转换成小写
-
例如:
'lice'→'lice'(如果原本是'ALICE',结果就是'lice')
6. concat(...)
-
作用:将首字母(大写)和其余部分(小写)拼接起来
-
例如:
'A' + 'lice'→'Alice'
select patient_id,
patient_name,
conditions
from Patients
WHERE conditions regexp '(^|\\s)DIAB1'
^表示字符串的开头。
\\s
-
\s是正则中的“空白字符”(whitespace)的意思,匹配空格、制表符、换行等。 -
在 SQL 字符串中,要写成
\\s才能正确传递\s给正则引擎(因为\是转义字符)。
(^|\\s)
-
表示:要么是字符串开头,要么是前面有空白符
-
即:匹配
DIAB1的前面是“行首”或“空格”
delete p2
FROM Person p1
JOIN Person p2
ON p1.email = p2.email
WHERE p2.id > p1.id
如果是选取较大的,就把delete换成select,所以看出两个用法都一样
select
(
select distinct salary
from Employee
order by salary desc
limit 1,1
)SecondHighestSalary
去重,这种select
( select
....
)用法感觉少见,但还是要掌握
1484. 按日期分组销售产品 - 力扣(LeetCode)
select sell_date,
count(distinct product) as num_sold,
group_concat(distinct product order by product) as products
from Activities
group by sell_date
order by sell_date
GROUP_CONCAT()聚合函数(像 SUM()、COUNT() 一样)用于在 GROUP BY 中,把多个记录的值合并为一个字符串,通常在分组后使用,用来把一个组内的多个值拼接起来,形成“逗号分隔列表”
将group_concat中的order by product去掉也行,emmm。
1327. 列出指定时间段内所有的下单产品 - 力扣(LeetCode)
SELECT p.product_name,
sum(o.unit) as unit
FROM Products p
JOIN Orders o
using (product_id)
where o.order_date between '2020-02-01' and '2020-02-29'
group by p.product_id
having sum(o.unit) >= 100
注意:按照严格的SQL标准,SELECT列表中的非聚合列必须出现在GROUP BY子句中。
但是这道题,product_id是主键,与product_name有依赖关系,所以也可以。
但是为了代码的可移植性和清晰性,建议还是遵循标准的GROUP BY规则
group by p.product_id,p.product_id
1517. 查找拥有有效邮箱的用户 - 力扣(LeetCode)
name,
mail
from Users
where mail regexp '^[a-zA-Z][a-zA-Z0-9-._]*@leetcode\\.com$'
注意:在正则表达式中,* 是一个量词,表示前面的字符或字符组可以出现 0次或多次。

浙公网安备 33010602011771号