MySQL數據表中的數據操做

一、插入數據sql

insert into t_user (username,password,nickname) values ('foye','123','佛爺');

如下方式必須寫出全部的字段函數

insert into t_user values (null,'eryuehong','456','二月紅');

能夠經過 insert into xxx select xxx 插入已有表中的數據code

insert into t_user(username,nickname) select no,name from t_student;

二、簡單查詢排序

select * from 表名table

查詢條件class

select * from 表名 where 條件date

select * from t_user;

 select id,username from t_user;

 select * from t_user where id>2;

 select * from t_user where id>2 and nickname='二月紅';

三、更新select

update 表名 set 字段名=新的值 where 條件im

update t_user set username='baye',nickname='八爺' where id=2;

四、刪除統計

delete from 表名 where 條件

delete from t_user where id=1;

使用truncate能夠清空表中的所有信息,並且能夠將自動遞增的標識清空

truncate table t_student;

五、經常使用查詢

like表示模糊查詢:like '張%' 模糊查詢張xx的數據

select * from t_stu where name like '李%'; (查詢姓名爲李xx的學生)

in表示某個值在某個數據中

select * from t_stu where cla_id in (1,2); (查詢在1和2班級中的學生)

between能夠查詢某個範圍內的數據

select * from t_stu where born between '1988-01-01' and '1989-12-30';
 (查詢出生日期在1988-01-01日至1989-12-30日的學生)

能夠經過一些函數進行查詢

select name as '姓名',year(now())-year(born) as '年齡' from t_stu where name like '李%';
 (查詢姓李的學生的姓名和年齡,as表示能夠爲投影取一個別名)

子查詢

select * from t_stu where born=(select min(born) from t_stu where cla_id=3 and sex='男');
 (查詢班級在3班的年齡最大的男生,注意最好將查詢條件放在子查詢裏)

查詢爲空的值應該使用 is null 而不是用 =null。

max()表示獲取最大值。

min()表示獲取最小值。

count()表示統計數量。

排序

select * from t_stu where cla_id=3 order by born desc;
 (經過出生日期的降序排序)
 select * from t_stu where cla_id=3 order by born;
 (默認狀況是經過升序排序,order by bord asc)

分組查詢(分組查詢主要用來統計相應的不一樣組別的信息)

select cla_id,count(id) from t_stu group by cla_id;
 (以上能夠分組獲取每一個班級中的學生總數)
 select cla_id,count(id),max(born),min(born) from t_stu where cla_id is not null group by cla_id;
 (經過班級進行分組,查詢每一個班級中年齡最大的值和年齡最小的值和班級的人數)
 (分組查詢中同樣是能夠加入查詢條件的)
 select cla_id,count(id) as pn,max(born),min(born) from t_stu where cla_id is not null group by cla_id having pn>60;
 (當比較的條件是在查詢出來的投影中時,不能使用where進行比較,而應該使用having進行比較,特別在group by常常使用)

六、跨表查詢(鏈接查詢)

一、相對較早的方式

select * from t_cla t1,t_stu t2 where t1.id = t2.cla_id and t1.id in (1,2,3);

較早的方式是經過where來鏈接幾個主鍵和外鍵的。

二、目前經常使用的方式

經常使用的方式是使用join和on來鏈接的,join表示將錶鏈接起來,on(鏈接的字段關係)

select t1.name,t2.name from t_cla t1 join t_stu t2 on (t1.id=t2.cla_id) where t1.id in (1,2,3);

內鏈接:直接使用join就是內鏈接。

左鏈接:left join

左鏈接是將左邊的這張表設置爲主表來鏈接右邊的表,若是左邊表中的數據在右表中沒有出現,會自動使用null來替代。

select t1.name,count(t2.id) from t_cla t1 left join t_stu t2 on (t1.id=t2.cla_id) group by t1.id;

右鏈接

右鏈接是將右邊的這張表設置爲主表來鏈接左邊的表,若是右邊表中的數據在左表中沒有出現,會自動使用null來替代。

select t1.name,count(t2.id) from t_cla t1 right join t_stu t2 on (t1.id=t2.cla_id) group by t1.id;

相關文章
相關標籤/搜索