想对一张表进行查询,知足任意一个条件便可,能够用union实现或查询。 java
id |
age |
gender |
1 |
20 |
female |
2 |
21 |
male |
3 |
22 |
male |
if(person.age > 22 || (person.age > 20 && person.gender == "female"){ System.out.println("达到法定要求准许结婚!"); }怎么样翻译成mysql语句呢,用union
select * from person p where p.age > 22 union 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放到最后一个的后面: mysql
(select * from person p where p.age > 22) union (select * from person p where p.age >20 and p.gender = "female") order by age limit 10;
怎样统计union以后的记录条数呢,天然会想到这个 sql
select count (*) from (select * from person p where p.age > 22 union select * from person p where p.age >20 and p.gender = "female");结果不行,后来查网上有说这样写的
select sum (cnt) from (select count(*) as cnt from person p where p.age > 22 union select count(*) as cnt from person p where p.age >20 and p.gender = "female");
结果仍是不行,都会报“Every derived table must have its own alias”这个错误,百度一下 spa
由于,进行嵌套查询的时候子查询出来的的结果是做为一个派生表来进行上一级的查询的,因此子查询的结果必需要有一个别名。 翻译
select count (*) from (select * from person p where p.age > 22 union select * from person p where p.age >20 and p.gender = "female")as total;
select sum (cnt) from (select count(*) as cnt from person p where p.age > 22 union select count(*) as cnt from person p where p.age >20 and p.gender = "female") as total;