create
table new_table select * from old_table
create
table new_table like old_table insert new_table select * from old_table
此外,如果想從另外表匯入資料:
insert
into table1(col1,col2,…) select col1, col2,… from table2
分頁在實際的專案中應用的十分廣泛, 但是當資料量大時, 其效率問題令人擔憂。先看下我們通常採用的分頁語句:
select * from
table
where …. order
by x limit start, size
select * from
table
where …. order
by x limit 10000, 10
隨著start的增大,查詢的效率越差, 需要進一步優化。
優化的方式主要有兩種方式1:子查詢2:連線查詢
select * from (select * from
table
where id>(select id from
table
order
by id desc limit 10000, 1) limit 10) order
by id desc
select * from
table
inner
join ( select id from
table
order
by id desc limit 10000,10) t2 using (id)
用儲存過程實現計算某使用者的排名
create
procedure
`calc_ranks `(username varchar(50)
begin
set @username = username;
prepare stmt fro
'select
cast(ranking.rank as signed)
from (
select @x := @x + 1
as rank, rd.username, rd.total
from ( select a.username, a.total
from table1 a left
join table2 b on a.username=b.user_name
where b.is_active = 1
and b.is_enabled = 1
order
by a.total desc, b.nick_name asc
) rd, (select @x := 0) r
) ranking
where ranking.username = ?';
execute stmt using @username;
end
匯出乙個表
mysql模糊查詢實踐總結
代表任意多個字元 代表乙個字元 在 mysql中,sql的模式預設是忽略大小寫的 正則模式使用regexp和not regexp操作符。匹配任何單個的字元。乙個字元類 匹配在方括號內的任意單個字元 匹配零個或多個在它前面的東西 正規表示式是區分大小寫的,但是如果你希望,你能使用乙個字元類匹配兩種寫法...
mysql樂觀鎖總結和實踐
樂觀鎖介紹 樂觀鎖 optimistic locking 相對悲觀鎖而言,樂觀鎖假設認為資料一般情況下不會造成衝突,所以在資料進行提交更新的時候,才會正式對資料的衝突與否進行檢測,如果發現衝突了,則讓返回使用者錯誤的資訊,讓使用者決定如何去做。那麼我們如何實現樂觀鎖呢,一般來說有以下2種方式 1.使...
mysql悲觀鎖總結和實踐
使用場景舉例 以mysql innodb為例 商品t goods表中有乙個欄位status,status為1代表商品未被下單,status為2代表商品已經被下單,那麼我們對某個商品下單時必須確保該商品status為1。假設商品的id為1。一 如果不採用鎖,那麼操作方法如下 1.查詢出商品資訊 sel...