MYSQL基礎02 查詢

2022-02-04 01:31:10 字數 3114 閱讀 1766

查詢是很大的一塊,所以這裡我只會寫mysql的特點,就我目前使用的情況,mysql對標準sql是比較支援,如果是新手的話,建議去w3school 學習標準sql.

1.dual

dual是乙個虛擬表,即該表是不存在的,用於直接select 標量時,使語句看起來符合sql規範

--

mssql

select

1,'a'--

oracle中dual 不可缺少

select

1,'a

'from

dual

--mysql 以下2種格式都支援

select

1,'a';

select

1,'a

'from dual;

2.limit

相對mssql來說,mysql並沒有top關鍵字,但有limit,而且效率更高且更靈活

select

*from usr limit 1;--

limit 1 的意思是取1條記錄, mysql在取完1條記錄後將不再操作.

select

*from usr limit 0,2;--

limit 0,2的意思是從第一行(包括第一行)開始,取2條記錄

select

*from usr where u_id in (select u_id from usr where dept=

'資訊部

' limit 1

);--

該語句執行時,mysql會報錯,意思是不能在子查詢中使用limit

--解決辦法,將使用limit的語句再套一層表即可;如下:

select

*from usr where u_id in (select

*from (select u_id from usr where dept=

'資訊部

' limit 1

)aa)

ps:mssql中使用top,資料庫會先排序,然後再返回資料,因此limit的效率比較高

3.子查詢的update錯誤

update usr set usr_name='匿名

'where u_id in (select u_id from usr where dept=

'資訊部')

--語句報錯,大概意思是修改表不能使用自身

--解決方法,跟上面一樣,再套一層表即可

update usr set usr_name='匿名

'where u_id in (select

*from (select u_id from usr where dept=

'資訊部

')aa)

4.變數宣告

mysql的查詢語句中,變數不需要宣告,直接賦值即可, @表示區域性變數(僅在當前會話有效) @@表示全域性變數

--

使用set 賦值有以下2種方法

set@num=1

;set

@num:=1;

--以下使用select 賦值

select

@num:=1;

以上三種方法效果是一樣的。

select

@num:=deptid from

dept

--查詢語句賦值

5.不報錯機制

用了一段時間後,發現mysql中一大特點就是一些常規的錯誤情況往往不報錯而正常執行。但是雖然正常執行,不過結果可能往往不是你想要的,所以我認為這並不是好事,正因為不報錯,導致一些錯誤情況而不知道。

--

①以0作除數

select1/

0--結果為null

--②插入日期欄位時,日期格式錯誤

insert

into mytable(created_date) values('

215-5-5

') --

插入值為'0000-00-00 00:00:00'

--③group by

select deptid,dname from dept group

bydname;

select deptid,max(dname) from dept group

bydname;

--以上語句mssql中會報錯,select的字段必須存在分組欄位中,但是mysql會正確執行,至於這樣的做法有什麼意義,我現在還沒明白

--④where條件中資料型別不一致

select

*from bill where b_id='a

';--說明:b_id 為int,mssql中會先將'a'轉換成數字,於是報錯; 而mysql會執行通過

select

*from dept where deptid=1;

--說明:deptid為varchar,mssql中會將1轉換成字元'1';執行正確

--而mysql會將deptid中含有'1'的資料都會過濾出來,執行類似於 like 的操作;因此如果要得到正確的資料,必須確保與deptid的型別一致,如下:

select

*from dept where deptid='1

'--最後強調在mysql中where 的條件語句中的左右字段型別必須相同,否則可能會得到你不想要的資料

6.獲取自增id

mysql中自增id有2種方法; 先執行插入語句,然後緊跟著執行以下語句

--

使用全域性變數@@identity,但是一般的程式應用中往往都會使用多個資料庫連線會話,所以全域性變數絕大部分情況是不合適的

select

@@identity

--使用last_insert_id(), 該函式是針對當前連線會話獲取最新插入的id,所以更合適一般程式的使用.

select last_insert_id()

使用select last_insert_id() 好像沒有問題,但是仍有講究的地方;在程式開發的過程中要確保"插入語句"和"獲取自增id"在同乙個會話中執行緊貼著執行; 如果使用批量插入 insert into mytable(name) values('name1'),('name2')  那麼last_insert_id()只獲取到第一條記錄的id

MySQL 基礎查詢高階02

高階 二 條件查詢 語法 select 查詢列表 from 表名字where 賽選條件 分類 一 按條件表示式賽選 條件運算子 二 按邏輯表示式查詢 主要作用就是連線條件表示式 邏輯運算子 and or not and 如果兩個條件都為真才為真 or 只要有乙個條件為真九為真 not 如果連線的條件...

MySQL筆記 02 基礎查詢

select 查詢列表 from 表名 類似於 system.out.println 列印內容 select last name from employees select last name,salary,email from employees 方式一 select employee id fi...

Mysql系列 基礎 02

特點 唯 一 非空 列級語法 欄位名 資料型別 primary key 預設值 create table student id int 20 primary key,name varchar 50 primary key,password varchar 30 表級語法 constraint 約束名...