- 如何处理SQL的多次排序?
题目:List the winners, year and subject where the winner starts with Sir. Show the the most recent first, then by name order.
题目中,最终列表需要先以年份排序,再以名字排序,存在两层排序顺序
select winner,yr,subject
from nobel
where winner like 'Sir%'
order by yr desc ,winner
- round函数:用于把数值字段舍入为指定的小数位数。
SELECT ROUND(column_name,decimals)
FROM table_name
- concat函数:将多个字符串连接为一个字符串
CONCAT(str1,str2...)
- all逻辑运算符:将单个值与子查询返回的单列值集进行比较
WHERE column_name comparison_operator ALL (subquery)
如果子查询不返回任何行,则WHERE子句中的条件始终为true;
c <> ALL(…),则c列中的值不得等于要评估为true的集合中的任何值。
- join用法:
select a
from table_1
join table_2 on table_1.idA=table_2.idB
select a
from table_1
join table_2 on (idA=idB)
- case when:then后面的值应与else后的值数据类型一致
函数:
case score when 'A' then '优' else '不合格' end
case score when 'B' then '良' else '不合格' end
case score when 'C' then '中' else '不合格' end
条件表达式:
case when score = 'A' then '优'
when score = 'B' then '良'
when score = 'C' then '中' else '不合格' end
- coalesce函数:返回第一个空值;将空值替换成其他值;遇到非null值即停止并返回该值。如果所有的表达式都是空值,最终将返回一个空值。
和ifnull函数的区别在于coalesce可以使用n个参数,若n=2,则和ifnull函数一致
select coalesce(expression_1,...,expression_n) from table_1
select coalesce('') from table_1
coalesce(name,1):若name为空值,则返回1,若不是空值,则返回name列对应值;
coalesce(name,1,2): 若name为空值,则返回1,若不是空值,则返回2;
coalesce(name,class,1):若name不是空值,则返回name;若name为空值,则返回class且class不是空值;若name、class都是空值,则返回1
- SQL中,字符串包含单引号或双引号怎么办?
包含单引号:在单引号旁边再增加一个单引号,外面用两个单引号包围
以Find all details of the prize won by EUGENE O’NEILL为例,
题目中 ,字符串EUGENE O’NEILL包含单引号
select *
from nobel
where winner = 'EUGENE O''NEILL'
包含双引号:在双引号旁边再增加一个双引号,外面用两个双引号包围
参考文章
sqlzoo学习地址:https://sqlzoo.net/wiki/Self_join_Quiz