续接上一篇博客秋招-SQL备战练习1(最后的冲刺)
备注:下文中的SQL语句使用与SQLite,也基本适用于MySQL中
用到的数据库表如下:
电影表film
CREATE TABLE IF NOT EXISTS film (
film_id smallint(5) NOT NULL DEFAULT '0',
title varchar(255) NOT NULL,
description text,
PRIMARY KEY (film_id));
电影类别表category
CREATE TABLE category (
category_id tinyint(3) NOT NULL ,
name varchar(25) NOT NULL, `last_update` timestamp,
PRIMARY KEY ( category_id ));
电影分类信息表film_category
CREATE TABLE film_category (
film_id smallint(5) NOT NULL,
category_id tinyint(3) NOT NULL, `last_update` timestamp);
演员表actor
CREATE TABLE IF NOT EXISTS actor (
actor_id smallint(5) NOT NULL PRIMARY KEY,
first_name varchar(45) NOT NULL,
last_name varchar(45) NOT NULL,
last_update timestamp NOT NULL DEFAULT (datetime('now','localtime')))
- 查找描述信息中包括robot的电影对应的分类名称以及电影数目,而且还需要该分类对应电影数量>=5部
select c.name,count(f.film_id)
from film f,film_category fc,category c,
(select category_id,count(fc.film_id) as f_count from film_category fc
group by category_id having f_count>=5)as fct
where description like '%robot%'
and f.film_id=fc.film_id
and fc.category_id=c.category_id
and fc.category_id=fct.category_id
group by c.category_id;
2.使用join查询方式找出没有分类的电影id以及名称
select film_id,title from
(select f.film_id,title,fc.category_id from film f
left join film_category fc on f.film_id=fc.film_id) as fct
where fct.category_id is null;
- 对于表actor批量插入如下数据,如果数据已经存在,请忽略,不使用replace操作
insert or ignore into actor values
('3','ED','CHASE','2006-02-15 12:34:33');
- 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。 actor_name表结构如下:
create table actor_name as
select first_name,last_name from actor;
- 在actor表,对first_name创建唯一索引uniq_idx_firstname,对last_name创建普通索引idx_lastname
create unique index uniq_idx_firstname on actor(first_name);
create index idx_lastname on actor(last_name);
6.针对actor表创建视图actor_name_view,只包含first_name以及last_name两列,并对这两列重新命名,first_name为first_name_v,last_name修改为last_name_v:
create view actor_name_view as
select first_name first_name_v,last_name last_name_v from actor;
- actor表中,现在在last_update后面新增加一列名字为create_date, 类型为datetime, NOT NULL,默认值为’0000-00-00 00:00:00’
alter table actor
add column create_date datetime not null default '0000-00-00 00:00:00';