Database SQL Exercise (1)


The Online Movies DataBase (OMDB) is as follows:
MovieInfo (mvID, title, rating, year, length, studio)
Director(directorID, firstname, lastname)
Member(username, email, password)
Actor(actorID, firstname, lastname, gender, birthplace)
Cast(mvID*, actorID*)
Direct(mvID*, directorID*)
Genre(mvID*, genre)
Ranking(username*, mvID*, score, voteDate)

a) Find the movies whose studio information is not available or whose genre
information is not available. List the movid and title of these movies. You must
use the NOT EXISTS operator. You must not use any SET operator (e.g. UNION,
MINUS)

Select mvID, title from MovieInfo WHERE NOT EXISTS( SELECT * FROM GENRE

WHERE GENRE.mvID = MoiveInfo.mvID) OR MovieInfo.studio is Null;

The differences between EXIST and IN in SQL Programming


in 和 exists也是很好区别的.

in 是一个集合运算符.

a in {a,c,d,s,d….}

这个运算中,前面是一个元素,后面是一个集合,集合中的元素类型是和前面的元素一样的.

而exists是一个存在判断,如果后面的查询中有结果,则exists为真,否则为假.

in 运算用在语句中,它后面带的select 一定是选一个字段,而不是select *.

比如说你要判断某班是否存在一个名为”小A”的学生,你可以用in 运算:

“小A” in (select sname from student)

这样(select sname from student) 返回的是一个全班姓名的集合,in用于判断”小明”是否为此集合中的一个数据;

同时,你也可以用exists语句:

exists (select * from student where sname=”小A”)

这两个涵数是差不多的, 但是由于优化方案的不同, 通常NOT EXISTS要比NOT IN 要快, 因为NOT EXISTS可以使用结合算法而NOT IN 就不行了,而EXISTS则不如IN快, 因为这时候IN可能更多的使用结合算法.

select * from 表A where exists(select * from 表B where 表B.id=表A.id)

这句相当于

select * from 表A where id in (select id from 表B)
对于表A的每一条数据,都执行select * from 表B where 表B.id=表A.id的存在性判断,如果表B中存在表A当前行相同的id,则exists为真,该行显示,否则不显示
exits适合内小外大的查询,in适合内大外小的查询

IN
确定给定的值是否与子查询或列表中的值相匹配。

EXISTS
指定一个子查询,检测行的存在。

比较使用 EXISTS 和 IN 的查询

这个例子比较了两个语义类似的查询。第一个查询使用 EXISTS 而第二个查询使用 IN。注意两个查询返回相同的信息。

USE pubs
GO
SELECT DISTINCT pub_name
FROM publishers
WHERE EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers.pub_id
AND type = ‘business’)
GO

– Or, using the IN clause:

USE pubs
GO
SELECT distinct pub_name
FROM publishers
WHERE pub_id IN
(SELECT pub_id
FROM titles
WHERE type = ‘business’)
GO

下面是任一查询的结果集:

pub_name
—————————————-
Algodata Infosystems
New Moon Books

(2 row(s) affected)