MySQL与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。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

DeepSeek: In-depth comparison between R1 and V3 versions helps you choose the best AI assistant! DeepSeek already has tens of millions of users, and its AI dialogue function has been well received. But are you confused when facing the R1 and V3 versions? This article will explain the differences between the two in detail to help you choose the most suitable version. The core difference between DeepSeekR1 and V3 version: Features The design goal of the V3 version focuses on complex problem reasoning, deep logic analysis, multi-functional large language model, focusing on scalability and efficiency architecture and parameter reinforcement learning optimization architecture, parameter scale 1.5 billion to 70 billion MoE hybrid Expert architecture, total parameters are as high as 671 billion, each token is activated by 37 billion

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI model through API or Ollama. What is breaking limit

The cryptocurrency market is booming, and Bitcoin, as a leader, has attracted the attention of many investors. Many people are curious: Do Bitcoin have stocks? The answer is no. Bitcoin itself is not a stock, but investors can indirectly invest in Bitcoin-related assets through various channels, which will be explained in detail in this article. Alternatives to Bitcoin Investment: Instead of investing directly in Bitcoin, investors can participate in the Bitcoin market by: Bitcoin ETF: This is a fund traded on the stock trading market, whose asset portfolio contains Bitcoin or Bitcoin futures contracts. This is a relatively convenient option for investors who are accustomed to stock investments, without having to hold Bitcoin directly. Bitcoin Mining Company Stocks: These companies' business is Bitcoin mining and holding Bitcoin

In traditional financial markets, pre-market and after-market trading refers to trading activities outside the regular trading period. Although the cryptocurrency market is trading around the clock, trading platforms like Bitget also offer similar features, especially some comprehensive platforms that trade stocks and cryptocurrencies at the same time. This article will clarify the differences in pre-market and after-market trading and explore its impact on currency price. Four major differences between pre-market and after-market trading: The main differences between pre-market and after-market trading and regular trading periods are in four aspects: trading time, liquidity, price fluctuations and trading volume: Trading time: Pre-market trading occurs before the official trading starts, and after-market trading is carried out after the regular trading ends. Liquidity: The liquidity of pre- and after-hours trading is low, there are few traders, and the bid and offer price difference is large; while the liquidity is high during the regular trading period, the price is

Original title: Bittensor=AIBitcoin? Original author: S4mmyEth, Decentralized AI Research Original translation: zhouzhou, BlockBeats Editor's note: This article discusses Bittensor, a decentralized AI platform, hoping to break the monopoly of centralized AI companies through blockchain technology and promote an open and collaborative AI ecosystem. Bittensor adopts a subnet model that allows the emergence of different AI solutions and inspires innovation through TAO tokens. Although the AI market is mature, Bittensor faces competitive risks and may be subject to other open source

The Bitcoin investment boom continues to heat up. As the world's first decentralized digital asset, Bitcoin has attracted much attention on its decentralization and global liquidity. Although China was once the largest market for Bitcoin, policy impacts have led to transaction restrictions. Today, South Korea has become one of the major Bitcoin markets in the world, causing investors to question the differences between it and its domestic Bitcoin. This article will conduct in-depth analysis of the differences between the Bitcoin markets of the two countries. Analysis of the differences between South Korea and China Bitcoin markets. The main differences between South Korea and China’s Bitcoin markets are reflected in prices, market supply and demand, exchange rates, regulatory supervision, market liquidity and trading platforms. Price difference: South Korea’s Bitcoin price is usually higher than China, and this phenomenon is called “Kimchi Premium.” For example, in late October 2024, the price of Bitcoin in South Korea was once

Artificial intelligence agents (AIAgents) are rapidly integrating into daily operations of enterprises, from large companies to small businesses, almost all areas have begun to be used, including sales, marketing, finance, law, IT, project management, logistics, customer service and workflow automation. We are moving from an era of manual processing of data, performing repetitive tasks, and using Excel tables to an era of autonomous operation by AI agents around the clock, which not only improves efficiency but also significantly reduces costs. Application case of AI agents in Web2: YCombinator's Perspective Apten: A sales and marketing optimization tool combining AI and SMS technology. BildAI: A model that can read architectural blueprints,

After the surge in PEPE, can MUTM become a more stable investment choice in 2025? PEPE (PEPE) has made early investors profitable, but its violent price fluctuations have also made many people question its long-term prospects. As the meme currency market continues to turbulently, traders are beginning to focus on projects with more fundamental advantages, and MutuumFinance (MUTM) is one of them. This is a decentralized lending platform focusing on practical financial applications. Unlike PEPE, which relies on speculative speculation, MUTM builds a structured DeFi ecosystem where users can borrow and earn passive income. Its pre-sale has exceeded one million US dollars, the first phase of token sales rate exceeds 97%, early investment
