search
HomeDatabaseMysql TutorialMySQL与Oracle的语法区别详细对比

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
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
How does MySQL handle concurrency compared to other RDBMS?How does MySQL handle concurrency compared to other RDBMS?Apr 29, 2025 am 12:44 AM

MySQLhandlesconcurrencyusingamixofrow-levelandtable-levellocking,primarilythroughInnoDB'srow-levellocking.ComparedtootherRDBMS,MySQL'sapproachisefficientformanyusecasesbutmayfacechallengeswithdeadlocksandlacksadvancedfeatureslikePostgreSQL'sSerializa

How does MySQL handle transactions compared to other relational databases?How does MySQL handle transactions compared to other relational databases?Apr 29, 2025 am 12:37 AM

MySQLhandlestransactionseffectivelyusingtheInnoDBengine,supportingACIDpropertiessimilartoPostgreSQLandOracle.1)MySQLusesREPEATABLEREADasthedefaultisolationlevel,whichcanbeadjustedtoREADCOMMITTEDforhigh-trafficscenarios.2)Itoptimizesperformancewithabu

How does MySQL differ from PostgreSQL?How does MySQL differ from PostgreSQL?Apr 29, 2025 am 12:23 AM

MySQLisbetterforspeedandsimplicity,suitableforwebapplications;PostgreSQLexcelsincomplexdatascenarioswithrobustfeatures.MySQLisidealforquickprojectsandread-heavytasks,whilePostgreSQLispreferredforapplicationsrequiringstrictdataintegrityandadvancedSQLf

How does MySQL handle data replication?How does MySQL handle data replication?Apr 28, 2025 am 12:25 AM

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

How can you use the EXPLAIN statement to analyze query performance?How can you use the EXPLAIN statement to analyze query performance?Apr 28, 2025 am 12:24 AM

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

How do you back up and restore a MySQL database?How do you back up and restore a MySQL database?Apr 28, 2025 am 12:23 AM

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

What are some common causes of slow queries in MySQL?What are some common causes of slow queries in MySQL?Apr 28, 2025 am 12:18 AM

The main reasons for slow MySQL query include missing or improper use of indexes, query complexity, excessive data volume and insufficient hardware resources. Optimization suggestions include: 1. Create appropriate indexes; 2. Optimize query statements; 3. Use table partitioning technology; 4. Appropriately upgrade hardware.

What are views in MySQL?What are views in MySQL?Apr 28, 2025 am 12:04 AM

MySQL view is a virtual table based on SQL query results and does not store data. 1) Views simplify complex queries, 2) Enhance data security, and 3) Maintain data consistency. Views are stored queries in databases that can be used like tables, but data is generated dynamically.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.