Home Database Mysql Tutorial MySQL与Oracle的语法区别详细对比

MySQL与Oracle的语法区别详细对比

Jun 07, 2016 pm 05:55 PM
the difference grammar

Oracle和mysql的一些简单命令对比在本文中将会涉及到很多的实例,感兴趣的你不妨学习一下,就当巩固自己的知识了

Oracle和mysql的一些简单命令对比
1) SQL> select to_char(sysdate,'yyyy-mm-dd') from dual;
  SQL> select to_char(sysdate,'hh24-mi-ss') from dual;
  mysql> select date_format(now(),'%Y-%m-%d');
  mysql> select time_format(now(),'%H-%i-%S');
  日期函数
  增加一个月:
  SQL> select to_char(add_months(to_date ('20000101','yyyymmdd'),1),'yyyy-mm-dd') from dual;
  结果:2000-02-01
  SQL> select to_char(add_months(to_date('20000101','yyyymmdd'),5),'yyyy-mm-dd') from dual;
  结果:2000-06-01
  mysql> select date_add('2000-01-01',interval 1 month);
  结果:2000-02-01
  mysql> select date_add('2000-01-01',interval 5 month);
  结果:2000-06-01
  截取字符串:
  SQL> select substr('abcdefg',1,5) from dual;
  SQL> select substrb('abcdefg',1,5) from dual;
  结果:abcdemysql> select substring('abcdefg',2,3);
  结果:bcd
  mysql> select mid('abcdefg',2,3);
  结果:bcd
  mysql> select substring('abcdefg',2);
  结果:bcdefg
  mysql> select substring('abcdefg' from 2);
  结果:bcdefg
2) 在MySQL中from 后的表如果是(select.......)这种,那么后面必须有别名
3) 连接字符串在Oracle中用|| ,SqlServer中用+,MySQL中用concat('a','b','c')

4)
在SqlServer中的写法:
代码如下:
declare @id varchar(50);
set @id='4028e4962c3df257012c3df3b4850001';
select * from sims_sample_detect where ID= @id;

在MySQL中的写法:
代码如下:
set @a = 189;
select * from bc_article where id = @a //不用declare

在Orcale中的写法:

5)MySQL存储过程:
代码如下:
DELIMITER $$
DROP PROCEDURE IF EXISTS `SIMS`.`transaction_delSampleInfo`$$
CREATE DEFINER=`root`@`%` PROCEDURE `transaction_delSampleInfo`(in sampleInfoId varchar(50))
BEGIN
start transaction;
update sims_sample_info set del='1' where ID = sampleInfoId;
update sims_sample_detect set del='1' where SAMPLE_ID_PARENT = sampleInfoId;
update sims_sample_detect_info set del='1' where DETECT_ID in(
select ID from sims_sample_detect where SAMPLE_ID_PARENT = sampleInfoId
);
commit;
END$$
DELIMITER ;

变量名不能跟列名相同,否则效果为1=1,且MySQL不区分大小写。

6)mysql 游标
mysql没有像orcale的动态游标,只有显示游标,例子如下:
代码如下:
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`liyukun`$$
CREATE DEFINER=`ids`@`localhost` PROCEDURE `liyukun`(out z int)
BEGIN
declare count1 int;
DECLARE done INT DEFAULT 0;
declare v_haoma varchar(50);
declare v_yingyeting varchar(100);
DECLARE cur1 CURSOR FOR select haoma,yingyeting from eryue where idDECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
//这里和oracle有区别,Oracle的PL/SQL的指针有个隐性变
量%notfound,Mysql是通过一个Error handler的声明来进行判断的
OPEN cur1;
cur1: LOOP
FETCH cur1 INTO v_haoma,v_yingyeting;
IF done=1 THEN //如果没有数据了,则离开
LEAVE cur1;
ELSE
select count(*) into count1 from year2012 where haoma=v_haoma ;
if(count1=0) then
insert into year2012(haoma, yingyeting)
values(v_haoma,v_yingyeting);
else
set z = z+1;
update year2012 set eryue = ‘100' where haoma=v_haoma;
end if;
END IF;
END LOOP cur1;
CLOSE cur1;
END$$
DELIMITER ;

执行:
代码如下:
call liyukun(@a);
select @a;

7) mysql的group by 语句可以select 没有被分组的字段,如
select id,name,age from A group by age 这样
但是在orcale和sqlserver中是会报错的。这个取出的id,name所在的行是每个分组中的第一行数据。
8)orcale用decode()来转换数据,mysql,sqlserver用case when:
case t.DETECT_RESULT when '2402' then t.SAMPLEID end (必须有end)
9)mysql: 两个select 出的数据相减:
(COUNT(distinct(t.SAMPLEID))-
CONVERT((COUNT(distinct(case t.DETECT_RESULT when '2402' then t.SAMPLEID end))), SIGNED)) AS NEGATIVE
FROM `view_sims_for_report` t
10)convert,cast用法
mysql将varchar转为int
convert(字段名, SIGNED)
字符集转换 : CONVERT(xxx USING gb2312)
类型转换和SQL Server一样,就是类型参数有点不同 : CAST(xxx AS 类型) , CONVERT(xxx,类型)
可用的类型 
二进制,同带binary前缀的效果 : BINARY
字符型,可带参数 : CHAR()
日期 : DATE
时间: TIME
日期时间型 : DATETIME
浮点数 : DECIMAL
整数 : SIGNED
无符号整数 : UNSIGNED
11)如果从mysql数据库中取的时候没有乱码,而在Java的List中得到的是乱码的话,那么可能是SQL语句中的有字段不是 varchar的数据类型,这时需要转换convert(字段名, 类型)转换一下,Orcale则用ToChar函数
12)Orcale的大字段用clob,图像用blob,clob字段在Hibernate的映射文件中用String就可以
13) mysql,orcale,sqlserver 语句执行顺序
开始->FROM子句->WHERE子句->GROUP BY子句->HAVING子句->ORDER BY子句->SELECT子句->LIMIT子句->最终结果
每个子句执行后都会产生一个中间结果 ,供接下来的子句使用,如果不存在某个子句,就跳过。
14) LPAD函数
1在oracle的数据库里有个函数 LPAD(String a,int length,String addString).
2作用:把addString添加到a的左边,length 是返回值的长度。
3例子
代码如下:
A : SQL> select lpad('test',8,0) from dual;
LPAD('TEST',8,0)
----------------
0000test
B: select lpad('test',8) from dual;
LPAD('TEST',8)
--------------
test 注:不写最后一个参数,函数会默认在返回值左边加一个空格。
C: SQL> select lpad('test',2,0) from dual;
LPAD('TEST',2,0)
----------------
te
D:SQL> select lpad('test',3) from dual;
LPAD('TEST',3)
--------------
tes

15)Orcale中没有TOP,是通过
select * from (select * from A order by id desc) where rownum=1
注:不能直接写 select * from A where rownum=1 order by id desc 因为语句执行的顺序是先where再order by ,如果这样写就无法按id的排序来取第一个了。
不能写rownum=2或rownum>1这样,因为Orcale 默认必须包含第一条。
如果非要取第二条的话,可以写成:
代码如下:
select * from (select id,rownum as row_num from lws_q_bl_result r where r.sample_id = 'B10226072') where row_num=2

16)Orcale,MySql while循环比较
Orcale:
代码如下:
while numloop
str := to_char(num);
num := num+1;
end loop;

也可以:
代码如下:
for num in 1..10 --这样的缺陷是无法间隔取值
loop
str := to_char(num);
end loop;

mysql:
代码如下:
while numdo
str := to_char(num);
num := num+1;
end while;

17)orcale 生成唯一序列是 select sys.guid() from dual ,mysql是 select uuid() from dual

18)MySql和Orcale的ID自增
MySql由于是在数据库中实现ID自增,所以如果想返回插入一条序列的该条ID,只能用如下方法:
代码如下:
public int insertSign(final SpaceSign sign) throws Exception {
try{
KeyHolder keyHolder = new GeneratedKeyHolder();
final String sql = "insert into space_sign(userId,userName,nickName,contentText,contentHtml,isPublic,commentCount,userIp,status,insertTime)" +
" values(?,?,?,?,?,?,?,?,?,?)";
template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, sign.getUserId());
ps.setString(2, sign.getUserName());
ps.setString(3, sign.getNickName());
ps.setString(4, sign.getContentText());
ps.setString(5, sign.getContentHtml());
ps.setInt(6, sign.getIsPublic());
ps.setInt(7,sign.getCommnetCount());
ps.setString(8, sign.getUserIp());
ps.setInt(9, sign.getStatus());
ps.setTimestamp(10, new java.sql.Timestamp(sign.getInsertTime().getTime()));
return ps;
}
}, keyHolder);
Long generatedId = keyHolder.getKey().longValue();
return generatedId.intValue();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new SQLException("发表签名失败", e);
}
}

由于Orcale的ID是在插入该条数据之前就通过select SEQ_BLOG_ID.nextval from dual 获得的,所以直接返回既可。ps:SEQ_BLOG_ID为在数据库中设置的sequence。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

How to set password protection for export PDF on PS How to set password protection for export PDF on PS Apr 06, 2025 pm 04:45 PM

Export password-protected PDF in Photoshop: Open the image file. Click "File"> "Export"> "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Apr 05, 2025 pm 01:03 PM

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

What are the differences and connections between c and c#? What are the differences and connections between c and c#? Apr 03, 2025 pm 10:36 PM

Although C and C# have similarities, they are completely different: C is a process-oriented, manual memory management, and platform-dependent language used for system programming; C# is an object-oriented, garbage collection, and platform-independent language used for desktop, web application and game development.

How to use XPath to search from a specified DOM node in JavaScript? How to use XPath to search from a specified DOM node in JavaScript? Apr 04, 2025 pm 11:15 PM

Detailed explanation of XPath search method under DOM nodes In JavaScript, we often need to find specific nodes from the DOM tree based on XPath expressions. If you need to...

What are the different ways of promoting H5 and mini programs? What are the different ways of promoting H5 and mini programs? Apr 06, 2025 am 11:03 AM

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.

See all articles