mysql或查询语句_MySQL

php中文网
发布: 2016-06-01 13:30:09
原创
1075人浏览过

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
相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号