
本节将简单介绍什么是计算字段,如何创建计算字段以及怎样从应用程序中使用别名引用它们
拼接字段
将值联结到一起构成单个值,Mysql 的 select 语句中,可使用
concat()
函数来拼接两个列
select concat(sname, '(', ssex , ')')
from student
order by sid;
输出为:
+----------------------------+
| concat(sname,'(',ssex,')') |
+----------------------------+
| 赵雷@(男) |
| 钱电@(男) |
| 孙风(男) |
| 李云(男) |
| 周红梅(女) |
| 吴红兰(女) |
| 郑竹(女) |
| 张三竹(女) |
| 李四(女) |
| 李四(女) |
| 赵六(女) |
| 孙七(女) |
+----------------------------+
concat()
拼接串,即把多个串连接起来形成一个较长的串,需要一个或多个指定的串,各个串之间用逗号分隔
Mysql 除了支持
RTrim()
(去掉串右边的空格),还支持LTrim()
(去掉串左边的空格)以及Trim()
(去掉串左右两边的空格)
使用别名
select concat(sname, '(', ssex , ')') as name_sex
from student
order by sid;
select 语句本身与以前使用的相同,只不过这里的语句中计算字段之后跟了文本 as name_sex,表示将列名改为了 name_sex 展示输出,输出为:
+----------------+
| name_sex |
+----------------+
| 赵雷@(男) |
| 钱电@(男) |
| 孙风(男) |
| 李云(男) |
| 周红梅(女) |
| 吴红兰(女) |
| 郑竹(女) |
| 张三竹(女) |
| 李四(女) |
| 李四(女) |
| 赵六(女) |
| 孙七(女) |
+----------------+
执行算术计算
select name, price, num, price * num as total_price
from goods
where price >5000
order by price;
输出为:
+---------------------------------------+-----------+------+-------------+
| name | price | num | total_price |
+---------------------------------------+-----------+------+-------------+
| poweredge ii服务器 | 5388.000 | 23 | 123924.000 |
| x3250 m4机架式服务器 | 6888.000 | 45 | 309960.000 |
| hmz-t3w 头戴显示设备 | 6999.000 | 4 | 27996.000 |
| svp13226scb 触控超极本 | 7999.000 | 5 | 39995.000 |
| g150th 15.6英寸游戏本 | 8499.000 | 12 | 101988.000 |
| imac me086ch/a 21.5英寸一体电脑 | 9188.000 | 56 | 514528.000 |
| mac pro专业级台式电脑 | 28888.000 | 7 | 202216.000 |
+---------------------------------------+-----------+------+-------------+
Mysql 算术操作符
操作符 | 说明 |
---|---|
+ | 加 |
- | 减 |
* | 乘 |
/ | 除 |
select 提供了测试和试验函数与计算的一个很好的办法。虽然 select 通常用来从表中检索数据,但可以省略 from 子句以便简单地访问和处理表达式。例如,select 3*2; 将返回 6,select Trim('abc'); 将返回 abc ,而 select Now() 利用 Now() 函数返回当前日期和时间。通过这些例子,可以明白如何根据需要使用SELECT进行试验
网友评论