• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

mysql或查询语句_MySQL

mysql 搞代码 4年前 (2022-01-09) 30次浏览 已收录 0个评论

gaodaima.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(*<strong style="color:transparent">来源gaodai#ma#com搞@代~码$网</strong>) 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;

gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:mysql或查询语句_MySQL

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址