Home >Database >Mysql Tutorial >mysql或查询语句_MySQL

mysql或查询语句_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-01 13:30:09921browse

bitsCN.com

mysql或查询语句

 

    想对一张表进行查询,满足任意一个条件即可,可以用union实现或查询。

idagegender120female221male322male

 

    比如说person表中满足年龄超过20岁的女性或者年龄超过22岁的男性,才可以结婚。我们用if这样写

1if(person.age > 22 || (person.age > 20 && person.gender == "female"){2    System.out.println("达到法定要求准许结婚!");3}怎么样翻译成mysql语句呢,用union1select * from person p where p.age > 222union select * from person p where p.age >20 and p.gender = "female";

 

注意:这里使用的是union不是union all,因为第二句查询的结果集里也会包涵第一句查询的结果集,使用union,则返回的行都是唯一的,如同您已经对整个结果集合使用了distinct,使用union all则不会排重返回所有的行。

如果您想使用ORDER BY或LIMIT子句来对全部UNION结果进行分类或限制,则应对单个地SELECT语句加圆括号,并把ORDER BY或LIMIT放到最后一个的后面:

 

1(select * from person p where p.age > 22)2union3(select * from person p where p.age >20 and p.gender = "female")4order by age limit 10;

 

怎样统计union之后的记录条数呢,自然会想到这个

 

1select count (*) from2(select * from person p where p.age > 223union select * from person p where p.age >20 and p.gender = "female");

 

结果不行,后来查网上有说这样写的

 

1select sum (cnt) from2(select count(*) as cnt from person p where p.age > 223union select count(*) as cnt from person p where p.age >20 and p.gender = "female");

 

结果还是不行,都会报“Every derived table must have its own alias”这个错误,百度一下

 

因为,进行嵌套查询的时候子查询出来的的结果是作为一个派生表来进行上一级的查询的,所以子查询的结果必须要有一个别名。

 

1select count (*) from2(select * from person p where p.age > 223union select * from person p where p.age >20 and p.gender = "female")as total;1select sum (cnt) from2(select count(*) as cnt from person p where p.age > 223union select count(*) as cnt from person p where p.age >20 and p.gender = "female") as total;

 


bitsCN.com
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn