秋招-SQL備戰練習2

續接上一篇博客秋招-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')))

在這裏插入圖片描述

  1. 查找描述信息中包括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;
  1. 對於表actor批量插入如下數據,如果數據已經存在,請忽略,不使用replace操作
    在這裏插入圖片描述
insert or ignore into actor values
('3','ED','CHASE','2006-02-15 12:34:33');
  1. 創建一個actor_name表,將actor表中的所有first_name以及last_name導入改表。 actor_name表結構如下:
    在這裏插入圖片描述
create table actor_name as 
select first_name,last_name from actor;
  1. 在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;
  1. 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';
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章