SQL里面的嵌套查询语句怎么写?
2个回答
展开全部
1,简单子查询;
select name,age from person
where age >
(
select age from person
where name = '孙权'
)
2,in嵌套查询;
select name from person
where countryid in
(
select countryid from country
where countryname = '魏国'
)
3,some嵌套查询
select name from person
where countryid = some --用等号和以下查询到的值比较,如果与其中一个相等,就返回
(
select countryid from country
where countryname = '魏国'
)
4,all嵌套查询
select name from person
where countryid > all --当countryid大于以下返回的所有id,此结果才为True,此结果才返回
(
select countryid from country
where countryname = '魏国'
)
5,exits嵌套查询
SELECT * FROM Person
WHERE exists
(
SELECT 1 --SELECT 0 SELECT NULL 返回结果都一样,因为这三个子查询都有结果集返回,因此总是True SELECT * FROM Person照常执行
)
但是如果子查询中因为加了条件而没有结果集返回,则主语句就不执行了:
SELECT * FROM Person
WHERE exists
(
SELECT * FROM Person
WHERE Person_Id = 100 --如果不存在Person_Id的记录,则子查询没有结果集返回,主语句不执行
)
select name,age from person
where age >
(
select age from person
where name = '孙权'
)
2,in嵌套查询;
select name from person
where countryid in
(
select countryid from country
where countryname = '魏国'
)
3,some嵌套查询
select name from person
where countryid = some --用等号和以下查询到的值比较,如果与其中一个相等,就返回
(
select countryid from country
where countryname = '魏国'
)
4,all嵌套查询
select name from person
where countryid > all --当countryid大于以下返回的所有id,此结果才为True,此结果才返回
(
select countryid from country
where countryname = '魏国'
)
5,exits嵌套查询
SELECT * FROM Person
WHERE exists
(
SELECT 1 --SELECT 0 SELECT NULL 返回结果都一样,因为这三个子查询都有结果集返回,因此总是True SELECT * FROM Person照常执行
)
但是如果子查询中因为加了条件而没有结果集返回,则主语句就不执行了:
SELECT * FROM Person
WHERE exists
(
SELECT * FROM Person
WHERE Person_Id = 100 --如果不存在Person_Id的记录,则子查询没有结果集返回,主语句不执行
)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询