1、使用sum() 求和
在编程中可以指定别名,方便使用。
select sum(math),sum(chinese) as schinese from tb_grade;
ResultSet set = statment.executeQuery();
while(set.next()){
System.out.println(set.getInt("sum(math)"));
System.out.println(set.getInt("schinese"));
}
2、使用max() 找到最大值(返回查询的字段)
mysql> select max(money) from tb_order;
+------------+
| max(money) |
+------------+
| 540000 |
+------------+
mysql> select * from tb_order where money in(select max(money) from tb_order);
+----+------+---------+--------+------------+
| id | name | address | money | oDate |
+----+------+---------+--------+------------+
| 5 | 小碗 | 北京 | 540000 | 2010-10-12 |
| 10 | a | b | 540000 | 2012-10-26 |
+----+------+---------+--------+------------+
2 rows in set
mysql> select count(price) as cnt from tb_booksell where price > 100;
+-----+
| cnt |
+-----+
| 3 |
+-----+
1 row in set
5、日期比较 很有用。 用to_days()
mysql> select * from tb_emp where to_days(ddate) > 10000;
+----+-----+------+------------+----------+------------+
| id | did | name | job | laborage | ddate |
+----+-----+------+------------+----------+------------+
| 1 | 1 | 张三 | 部门经理 | 5600 | 2012-10-17 |
| 2 | 1 | 李四 | 软件工程师 | 4800 | 2012-10-03 |
| 3 | 2 | 小刘 | 部门经理 | 6800 | 2012-11-07 |
| 4 | 3 | 小张 | 测试工程师 | 7800 | 2012-10-01 |
| 5 | 4 | 小李 | 部门经理 | 7900 | 2012-10-11 |
| 6 | 5 | 小葛 | 部门经理 | 5600 | 2012-10-23 |
| 7 | 5 | 小马 | 业务员 | 6500 | 2012-10-23 |
+----+-----+------+------------+----------+------------+
7 rows in set
mysql> select * from tb_emp where to_days(ddate) > to_days('2012-10-10');
+----+-----+------+----------+----------+------------+
| id | did | name | job | laborage | ddate |
+----+-----+------+----------+----------+------------+
| 1 | 1 | 张三 | 部门经理 | 5600 | 2012-10-17 |
| 3 | 2 | 小刘 | 部门经理 | 6800 | 2012-11-07 |
| 5 | 4 | 小李 | 部门经理 | 7900 | 2012-10-11 |
| 6 | 5 | 小葛 | 部门经理 | 5600 | 2012-10-23 |
| 7 | 5 | 小马 | 业务员 | 6500 | 2012-10-23 |
6、排序就不多说了。看下多条件查询。
如果第一个字段相等,就按第二个字段排序。
mysql> select * from tb_emp order by ddate desc,laborage asc;
+----+-----+------+------------+----------+------------+
| id | did | name | job | laborage | ddate |
+----+-----+------+------------+----------+------------+
| 3 | 2 | 小刘 | 部门经理 | 6800 | 2012-11-07 |
| 6 | 5 | 小葛 | 部门经理 | 5600 | 2012-10-23 |
| 7 | 5 | 小马 | 业务员 | 6500 | 2012-10-23 |
| 1 | 1 | 张三 | 部门经理 | 5600 | 2012-10-17 |
| 5 | 4 | 小李 | 部门经理 | 7900 | 2012-10-11 |
| 2 | 1 | 李四 | 软件工程师 | 4800 | 2012-10-03 |
| 4 | 3 | 小张 | 测试工程师 | 7800 | 2012-10-01 |
+----+-----+------+------------+----------+------------+