- 使用My’SQL数据库中的数据进行减法运算时,
- 不是不可以,要注意: 比如说我当前两张表是这样的:
一个是theorder用来存放订单,一个是product用来存放产品,想求库存量,需要用product表中的amount减去theorder表中对应产品的被订购的数量总和。
我开始写成了这样:
select (product.amount-select sum(theorder.amount) from theorder where productID=3) as inventory where
-> product.ID=3 from product;
看着蛮正常的,人就是说这语句有毛病:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select sum(theorder.amount) from theorder where productID=3) as inventory where ’ at line 1
然后我改,分步写:
反正分开好着整一起就不行了。
后来网上搜了一下,分别select出来,然后再把减完的结果select出来,就成了:
select(
(select product.amount as s2)
- (select sum(theorder.amount) as s1 from theorder where productID=3)
)
as inventory from product where I
(然鹅乘法我想用这套路,搞不了。)
- 和小明学的,为了不重复建表:
create table if not exists ohh
(......);
- 还可以在建表时设置字符集,这样就可以正常显示汉字而不是???了:
create table if not exists theOrder(ID int primary key auto_increment,clientID int,number int,orderDate date,productID int,amount int)default charset=utf8
- 数据库SQL实战之 查找最晚入职员工的所有信息
思路:
首先需要找到入职日期最大的那个员工信息:
select max(hire_date) from employees;
这只是找到了“最大入职日期”,接下来需要找到“最大入职日期对应的员工”:
select * from employees
where hire_date =
(select max(hire_date) from employees);
(注意括号。)
- 数据库SQL实战之 查找入职员工时间排名倒数第三的员工所有信息。
思路:先将员工入职时间降序排列,再生成一个从“1”开始自增1的列,然后选出“1”,“2”,“3”对应的员工信息。
有个函数“ROW_NUMBER”支持这样的功能:为结果集的每一行增加一个行号,但是这是8.0版本以后才支持的:
应该使用limit子句约束要返回的最大行数"1",配合offset指定偏移量(从"0"开始)“2”:
select * from employees
order by hire_date desc
limit 1 offset 2;