Leetcode SQL精选题(五)

114 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

最早的时候,SQL 作为一门查询数据库的语言,是程序员的必备技能,毕竟只有查询到正确的数据,才能有后面的数据加工、分析。在面试中,SQL 的考察也是一道必不可少的坎儿。通过这 70 题的专项练习,可以帮你打下坚实的「数据库」基础。 现在我在这里刷的题目有一部分是leetcode的sql练习每日计划里面的,其中有些答案用到的技巧还是蛮不错的.

25.为什么有时候不允许有两个相同的列名?

情况1:当你做一个简单的left join的时候,其实你使用的是拼接,应该没有产生一个新的表

情况2:在join之后,又在外面做了一个select,这个时候应该是产生了一个新的表,这样的话,如果其中的字段名重复了,就是不行的

26.year和sum的函数妙用

注意:在这里不能直接用year(order_date)进行统计,因为那样会导致出来的可能会是sum(null),这个恒为0

select user_id buyer_id, join_date,

sum(if(year(order_date)='2019',1,0)) orders_in_2019

from users left join orders

on user_id = buyer_id

group by user_id

27.mysql using

using等价于join操作中的on,例如a和b根据id字段关联,那么以下等价

`` using(id)

on a.id=b.id ``

以下2个实例等价:

select a.name,b.age from test as a

join test2 as b

on a.id=b.id
select a.name,b.age from test as a

join test2 as b

using(id)

28.mysql between

having sum(sale_date between "2019-01-01" and "2019-03-31") = count(sale_date)

select table.c1 between a1 and a2 as out from table

这个得用sum:因为返回的是1或0,关于是否满足这个between条件

select


product_id,

product_name


from product

join sales

using(product_id)


group by product_id

having( sum(sale_date between '2019-01-01' and '2019-03-31')=count(sale_date))

29.limit妙用 

排序之后limit 1,1得到第二大的值