• leetcode连接

    • https://leetcode.cn/problems/validate-ip-address/description/

  • 题目描述

func validIPAddress(queryIP string) string {
if strings.Index(queryIP,".") >0 {
// 验证是否是ipv4
if isIpv4(queryIP){
return "IPv4"
}
return "Neither"
}


if strings.Index(queryIP,":") > 0 {
// 验证是否是ipv6
if isIpv6(queryIP){
return "IPv6"
}
return "Neither"
}
return "Neither"
}


func isIpv6(queryIP string) bool{
var arr []string = strings.Split(queryIP,":")
if len(arr)!=8 {
return false
}
for i:=0;i<len(arr);i++ {
if !ipv6Helper(arr[i]){
return false
}
}
return true
}


func ipv6Helper(ip string) bool{
if len(ip)==0 || len(ip)>4{
return false
}
// 将16进制的ip转为int64看是否可以转 ,如果不能转,则返回err!=nil
_,err := strconv.ParseInt(ip,16,64)
return err == nil
}




func isIpv4(queryIP string) bool{
var arr []string = strings.Split(queryIP,".")
if len(arr)!=4 {
return false
}
for i:=0;i<len(arr);i++ {
if !ipv4Helper(arr[i]){
return false
}
}
return true
}


func ipv4Helper(ip string) bool{
if len(ip)==0 || len(ip)>3 {
return false
}
if ip[0]=='0' && len(ip)!=1{
return false
}
// 将ip转为十进制的int
i,err := strconv.Atoi(ip)
if err != nil {
return false
}
return i>=0 && i<=255
}
  • 解题思路

    • 通过left join + where is not null 过滤出在product表中的数据

    • 通过group by + count(distinct(xxx)) 来过滤出所有商品

select c.customer_id
from customer c left join product p on c.product_key = p.product_key
where p.product_key is not null # 排除用户购买了一些不在product表中的商品
group by c.customer_id
# 同一个用户可能买了一个商品多次,因此通过distinct去重
having count(distinct(p.product_key)) = (
# 所有产品的数量
select count(*)
from product
)



  • 题目描述

    • 合作过至少三次的演员和导演

  • 解题思路

    • 按照演员id和导演id进行分组,多字段分组必须要所有字段一致才会分到同一组 

select actor_id,director_id
from actordirector
group by actor_id,director_id
having count(*) >=3



  • 题目描述

    • 体育馆的人流量

  • 解题思路

    • 需要连续自增的三个id的时候,可以通过id = id-1,id=id-2进行leftjoin

    • union 具有去重功能, union all 不会进行去重

    • 当我们查询的时候需要一些中间表的时候,这个中间表必须要起一个别名

select *
from(
select s1.*
from stadium s1 left join stadium s2 on s1.id = s2.id-1
left join stadium s3 on s1.id = s3.id-2 # 这个from语句体现了连续的id
where s2.id is not null and s3.id is not null and s1.people>=100 and s2.people>=100 and s3.people>=100
union
select s2.*
from stadium s1 left join stadium s2 on s1.id = s2.id-1
left join stadium s3 on s1.id = s3.id-2
where s2.id is not null and s3.id is not null and s1.people>=100 and s2.people>=100 and s3.people>=100
union
select s3.*
from stadium s1 left join stadium s2 on s1.id = s2.id-1
left join stadium s3 on s1.id = s3.id-2
where s2.id is not null and s3.id is not null and s1.people>=100 and s2.people>=100 and s3.people>=100
) tmp order by id