荐 牛客网sql练习题解(43-51)

2022-08-09,,

文章目录

    • 简介
    • NO.43
    • NO.44
    • NO.45
    • NO.46
    • NO.47
    • NO.48
    • NO.49
    • NO.50
    • NO.51

简介

往期文章:
牛客网sql练习题解 (1-11)
牛客网sql练习题解(12-21)
牛客网sql练习题解(22-32)
牛客网sql练习题解(34-42)

他来了他来了,他带着sql走来了。

这次的知识点涵盖

  • update用法
  • replace函数
  • replace into
  • 修改表名
  • 外键
  • intersect用法

下面我们直接上题目。

NO.43

update titles_test set to_date=null, from_date='2001-01-01' where to_date='9999-01-01';

NO.44

这题考察replace into的用法.
使用replace两种方法,如果直接使用REPLACE INTO的话,就需要重新插入一条完整的新纪录,sql会自动代替id相同的记录;也可以使用UPDATE结合,REPLACE(colname,oldval,newval)来赋值给colnamejik

replace into titles_test values(5, 10005,  'Senior Engineer', '1986-06-26', '9999-01-01');

或者

replace into titles_test
select 5, 10005, title, from_date, to_date
from titles_test
where id=5;

NO.45

alter table titles_test rename to titles_2017;

NO.46

alter table audit
add foreign key(emp_no) references employees_test(id);

这种写法肯定是没有问题的啊,但是就是过不了,然后看了看其他同学的答案,原来OJ的问题。

然后写法二,这种写法我觉也就是为了过题 吧,真正用的话没人先删表。

drop table audit;

create table audit(
    emp_no int not null,
    create_date datetime not null,
    foreign key(emp_no) references employees_test(id)
);

NO.47

这题我真的没看懂,凭我的理解写了第一个答案:

select * from emp_v; 

骂街了,他在干嘛。

要不用交集做?

select * from emp_v intersect select * from employees;

这题,我觉得没什么东西。

NO.48

update salaries
set salary = salary * 1.1 
where to_date = '9999-01-01' 
    and emp_no in (select emp_no 
                   from emp_bonus);

跟着他的题目要求写没有什么困难。

NO.49

select "select count(*) from" || name || ";" as cnts
from sqlite_master
where type = "table";

其中的重点是怎么获取表明,也就是要知道不同的DBMS中的表名存储在哪里,
其中sqlite就找到sqlite_mater,如果是mysql就从information_schema.tables 获取表名。

NO.50

这题我觉得只需要知道sqlite用的是||连接字符串就可以了。

select last_name || "'" || first_name as name
from employees;

NO.51

说实话我一开始并不太理解这题什么意思,然后一看这不就是两个吗,然后我就震惊了:

select 2 as cnt;

这题确实我参考了其他的网友,因为平时replace用得少,而且没见过这种题,学习了。
考察replace和length函数的用法,
我们用length(原字符串) - length(replace(将,删掉)),这样就可以得到出现","的次数。

select (length('10,A,B') - length(replace('10,A,B',',',''))) as cnt;

大家共勉~~

本文地址:https://blog.csdn.net/qq_40742298/article/details/107135282

《荐 牛客网sql练习题解(43-51).doc》

下载本文的Word格式文档,以方便收藏与打印。