您的位置:首页 > 数据库 > MySQL

mysql 复合查询

2018-03-09 10:18 302 查看
MySQL 的复合查询或者嵌套查询,有表两张,要以 clrTheme 表两张为表列,将 clrColor 横向列出,故选择嵌套查询。

MySQL 复合嵌套查询命令如下

select * from clrTheme as t1,
(
(select * from clrColor where `sort` = 0) as c1,
(select * from clrColor where `sort` = 1) as c2,
(select * from clrColor where `sort` = 2) as c3,
(select * from clrColor where `sort` = 3) as c4,
(select * from clrColor where `sort` = 4) as c5
) where
t1.clrThemeId = c1.clrThemeId
and t1.clrThemeId = c2.clrThemeId
and t1.clrThemeId = c3.clrThemeId
and t1.clrThemeId = c4.clrThemeId
and t1.clrThemeId = c5.clrThemeId
order by t1.clrGroupId, t1.sort asc;


查询结果将以 clrTheme 为主列,将 clrColor 作为子列,根据条件得到结果。

这里针对 clrColor 的内查询建议加条件,以提高性能。

简单子查询

select name,age from person
where age >
(
select age from person
where name = '孙权'
)


in嵌套查询

 in关键字用于where子句中用来判断查询的表达式是否在多个值的列表中。返回满足in列表中的满足条件的记录。

select name from person
where countryid in
(
select countryid from country
where countryname = '魏国'
)


some 嵌套查询

some在sql中的逻辑运算符号,如果在一系列比较中,有些值为True,那么结果就为True。some的语法是:

<表达式>{ =|<>|!=|>|>=|!>|<|<=|!<}some(子查询)


例子:

select name from person
where countryid = some       --用等号和以下查询到的值比较,如果与其中一个相等,就返回
(
select countryid from country
where countryname = '魏国'
)


all 嵌套查询

 all是sql中的逻辑运算符好,如果一系列的比较都为true,那么结果才能为true。

 

<表达式>{ =|<>|!=|>|>=|!>|<|<=|!<}all(子查询)


例子:

select name from person
where countryid > all   --当countryid大于以下返回的所有id,此结果才为True,此结果才返回
(
select countryid from country
where countryname = '魏国'
)


exists嵌套查询

1、语法

   exists是sql中的逻辑运算符号。如果子查询有结果集返回,那么就为True。exists代表“存在”的意义,它只查找满足条件的那些记录。一旦找到第一个匹配的记录后,就马上停止查找。

其中子查询是一个首先的select语句,不允许有compute子句和into关键字。

   exists 的意思是,子查询是否有结果集返回。

   例如:

   

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的记录,则子查询没有结果集返回,主语句不执行
)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysq 嵌套 查询