1迈着、復(fù)制表( 只復(fù)制結(jié)構(gòu), 源表名:a新表名:b)
select * into b from a where 1=2;
將表結(jié)構(gòu)都復(fù)制到新表中
在mysql中上述語句報錯:Undeclared variable: b
原因:在mysql中不支持select * into b from a這種語法
改進(jìn):1、create table b select * from a
2、insert into b select * from a
這種語法是將a表的所有語法復(fù)制到b表中惕橙,前提是b表已經(jīng)存在了
從多個表中查詢數(shù)據(jù)
INSERT INTO a(field1,field2)
SELECT * FROM (SELECT f1,f2 FROM b JOIN c) AS tb
tb存在的意義:在mysql中任何一個派生出來的新表都必須有別名
3挂据、mysql在插入數(shù)據(jù)前判斷數(shù)據(jù)是否存在食寡,若不存在,再插入
語法:
INSERT INTO movie ( id, category )
SELECT 1,11
FROM dual
WHERE
NOT EXISTS ( SELECT * FROM movie WHERE id = 4 );
(1)dual:dual 是一張?zhí)摂M表用來構(gòu)成select語句的語法規(guī)則列敲,mysql中,dual表中沒有任何數(shù)據(jù)帖汞,只是構(gòu)成完整的語法規(guī)則戴而。oracle保證dual里面只有一條記錄。
(2)from dual:上面的代碼中翩蘸,from dual可以刪除不寫所意,原代碼仍然可以運行成功,
原因:在Mysql和SQL Server中可以直接:
select 1 不需要加from 表名就可以執(zhí)行
(3)把dual表換成movie表催首,如果movie表中有3條記錄扶踊,那么執(zhí)行此語句后,movie表中會被添加3條記錄(1,11)郎任,原因姻檀,當(dāng)判斷where not exists時,會對movie表的每一條記錄執(zhí)行一次:where not exists(select * from movie where id=4)涝滴。
當(dāng)不寫from movie 或換成 from dual時绣版,只會單獨執(zhí)行后面的where子句胶台,對一個movie整體執(zhí)行依稀where,所以此時只添加一條記錄杂抽。
關(guān)于exists:
1诈唬、最常用的if not exists
create table if not exists A
如果表A不存在(返回true)則創(chuàng)建表
2、select 語句中使用exists
select a.id,a.name from user
where exists (select * from class where a.class_id = c.class_id)