1 插入資料
這條語句可以同時插入多條資料,若為所有欄位插入資料,則column_list可以省略掉。
INSERT INTO table_name (column_list) VALUES (value_list1)[, (value_list2)...];
2 修改資料
UPDATE table_name
SET column_name1 = value1,
column_name2=value2,……,
column_namen=valueN
WHERE (condition);
3 刪除資料
若無where 條件則刪除所有資料
DELETE FROM table_name [WHERE condition] ;
4 查詢資料
a 單表查詢
語法規範:
SELECT {*|<欄位列表>} [
from <表1>, <表2>...
[where <condition>]
[group by <group by definition>]
[having <expression> [{<operator> <expression>...}]]
[order by <order by definition>]
[limit [<offset>,] <row count>]
]
1. 查詢所有欄位
select * from mytable1;
2. 查詢指定欄位
select id, name from mytable1;
3. 篩選
select id, name from mytable1 where id=3;
select id, name from mytable1 where id in (1, 2);
select id, name from mytable1 where id between 1 and 3; //這裡包括1-3之間的所有值
select id, name from mytable1 where name like 'b%';
select id, name from mytable1 where name like 'b__';
select id, name from mytable1 where name is not null;
select id, name from mytable1 where id in (1, 2) and name is not null;
select id, name from mytable1 where id=1 or id=2; //可以實現in功能,不過in效率更高
select distinct name from mytable1; //消除重複值
4. 排序,desc只對其前面的一個欄位生效,如果要對每一個欄位都降序,則每個欄位後都要加desc
單列排序
select age from mytable1 order by age;
多列排序:
select age, score from mytable1 order by score, age;
5. 分組
select id, group_concat(name) as names from mytable1 group by id having count(name)>1;
統計分組數目:
group by id with rollup;(該命令無法與order by一起使用)
6. 限制返回結果
limit 3,5; //第四行開始,共5行
7. 集合函式
count(), sum(), avg(),min(), max()等等,他們不包含NULL所在的行。
b 多表查詢
1. 內連線查詢
select mytable1.id, mytable1.name, mytable2.id, mytable2.name
from mytable1 inner join mytable2
on mytable1.id=mytable2.id;
2. 外連線查詢
左連線
select mytable1.id, mytable1.name, mytable2.id, mytable2.name
from mytable1 left outer join mytable2
on mytable1.id=mytable2.id;
右連線
select mytable1.id, mytable1.name, mytable2.id, mytable2.name
from mytable1 right outer join mytable2
on mytable1.id=mytable2.id;
c 子查詢
1. ANY, SOME為同義詞,表示有一個滿足即可
2. all 表示要滿足所有條件才行
3. exits 存在為true, 否則為false
4. in 內層查詢返回列表與外層比較
5. 帶比較運算子的子查詢
d 合併查詢
union 重複的行被刪除
union all 重複的行不被刪除,效率比union高
e 使用正規表示式查詢regexp
select * from mytable1 where name regexp '^b*a$';