条件与排序查询
①where子语句
一般格式:
select 字段 from 表名 where 条件
复制
(1)字段值和固定值比较,例如:
select name,height from mess where name='李四'
复制
(2)字段值在某个区间范围,例如:
select * from mess where height>1.60 and height<=1.8
select * from mess where height>1.7 and name != '张山'
复制
(3)使用某些特殊的日期函数,如year、month、day:
select * from mess where year(birthday)<1980 and month (birthday)<=10
select * from mess where year(birthday) between 1983 and 1986
复制
(4)使用某些特殊的时间函数,如hour、minute、second:
select * from time_list where second(shijian)=56;
select * from time_list where minute(shijian)>15;
复制
(5)用操作符like进行模式匹配,使用%代替0个或多个字符,用一个下画线_代替一个字符。例如,查询name有“林”字的记录:
select * from mess where name like '%林%'
复制
②排序
用order by子语句对记录进行排序,例如:
select * from mess order by height
select * from mess where name like '%林%' order by name
复制
例子3查询mess表中姓张,身高大于1.65,出生的年份在2000年或2000之前,月份在7月之后的学生,并按出生日期排序(在运行例子3程序前,我们使用MySQL客户端管理工具又向mess表添加了一些记录)。程序代码如下所示(例子3中使用了例子2中的GetDBConnection类)。
import java.sql.*;
public class Example3 {
public static void main(String[] args) {
Connection con;
Statement sql;
ResultSet rs;
con = GetDBConnection.connectDB("students","root","");
if(con == null) return;
String c1 = " year(birthday)<=2000 and month(birthday)>7"; //条件 1
String c2 = " name Like '张_%'"; //条件2
String c3 = "height >1.65"; //条件3
String sqlstr = "select * from mess where "+c1+" and "+c2+" and "+c3+"order by birthday";
try {
sql=con.createStatement();
rs = sql.executeQuery(sqlstr);
while (rs.next()) {
String number = rs.getString(1);
String name = rs.getString(2);
Date date = rs.getDate(3);
float h = rs.getFloat(4);
System.out.printf("%s\t",number);
System.out.printf("%s\t",name);
System.out.printf("%s\t",date);
System.out.printf("%.2f\n",h);
}
con.close();
}
catch (SQLException e) {
System.out.println(e);
}
}
}
复制
程序运行效果如图所示




文章转载自凯哥的故事,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
MySQL数据库当前和历史事务分析
听见风的声音
376次阅读
2025-04-01 08:47:17
墨天轮个人数说知识点合集
JiekeXu
372次阅读
2025-04-01 15:56:03
MySQL 生产实践-Update 二级索引导致的性能问题排查
chengang
347次阅读
2025-03-28 16:28:31
3月“墨力原创作者计划”获奖名单公布
墨天轮编辑部
300次阅读
2025-04-15 14:48:05
MySQL8.0直方图功能简介
Rock Yan
277次阅读
2025-03-21 15:30:53
MySQL 有没有类似 Oracle 的索引监控功能?
JiekeXu
267次阅读
2025-03-19 23:43:22
云和恩墨杨明翰:安全生产系列之MySQL高危操作
墨天轮编辑部
259次阅读
2025-03-27 16:45:26
MySQL 9.3 正式 GA,我却大失所望,新特性亮点与隐忧并存?
JiekeXu
249次阅读
2025-04-15 23:49:58
openHalo问世,全球首款基于PostgreSQL兼容MySQL协议的国产开源数据库
严少安
243次阅读
2025-04-07 12:14:29
PG vs MySQL 执行计划解读的异同点
进击的CJR
169次阅读
2025-03-21 10:50:08