常用SQL语句

时间:2022-06-19
本文章向大家介绍常用SQL语句,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

条件查找语句

sql语句:
根据条件查询出ann_id字段不同的数量
1.Select COUNT(distinct ann_id) from dmdb.t_bond_ann_att_info where last_update_time >= '2018-03-09 14:00:00';

根据条件查询id字段的数量
2.Select COUNT(id) from dmdb.t_bond_ann_info where create_time >= '2018-03-09 14:00:00';

查询a表中的id不在t_bond_ann_att_info这个表中的ann_id字段中
3.Select a.* from
dmdb.t_bond_ann_info a
where a.id not in (
select ann_id from  t_bond_ann_att_info
  where last_update_time >= '2018-03-09 14:00:00'   
)
and  a.create_time >= '2018-03-09 14:00:00';

4.Select distinct a.ann_id from 
dmdb.t_bond_ann_att_info a
where a.ann_id not in (
select id from  t_bond_ann_info
  where create_time >= '2018-03-09 11:10:00'   
)
and last_update_time >= '2018-03-09 11:10:00';

查询ann_id字段中,在所给的条件中
5.select  * from t_bond_ann_att_info where ann_id in ('13441','13442')

删除ann_id字段中,在所给的条件中
6.delete from t_bond_ann_att_info where ann_id in ('13441','13442')

按创建时间进行排序,显示800条
7.Select * from dmdb.t_bond_ann_info 
order by  create_time DESC
limit 800

t_bond_ann_att_info表中id5068所有字段内容
8.select * from dmdb.t_bond_ann_att_info where ann_id=15068

重复查找语句

1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断

select * from people
where peopleId in (select  peopleId  from  people  group  by  peopleId  having  count(peopleId) > 1)

 例二:

 select * from testtable
 where numeber in (select number from people group by number having count(number) > 1 )

 可以查出testtable表中number相同的记录

2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录
delete from people 
where peopleId  in (select  peopleId  from people  group  by  peopleId   having  count(peopleId) > 1)
and rowid not in (select min(rowid) from  people  group by peopleId  having count(peopleId )>1)

3、查找表中多余的重复记录(多个字段) 
select * fromvitae a
where (a.peopleId,a.seq) in  (select peopleId,seq from vitae group by peopleId,seq  having count(*) > 1)

4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录
delete fromvitae a
where (a.peopleId,a.seq) in  (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)

5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录
select * fromvitae a
where (a.peopleId,a.seq) in  (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)

(二)
比方说在A表中存在一个字段“name”,而且不同记录之间的“name”值有可能会相同,
现在就是需要查询出在该表中的各记录之间,“name”值存在重复的项;
Select Name,Count(*) From A Group By Name Having Count(*) > 1

如果还查性别也相同大则如下:
Select Name,sex,Count(*) From A Group By Name,sex Having Count(*) > 1

方法二
有两个意义上的重复记录,一是完全重复的记录,也即所有字段均重复的记录,二是部分关键字段重复的记录,
比如Name字段重复,而其他字段不一定重复或都重复可以忽略。
1、对于第一种重复,比较容易解决,使用
select distinct * from tableName
就可以得到无重复记录的结果集。

如果该表需要删除重复的记录(重复记录保留1条),可以按以下方法删除
select distinct * into #Tmp fromtableName
drop tabletableName
select * into tableName from#Tmp
drop table #Tmp

发生这种重复的原因是表设计不周产生的,增加唯一索引列即可解决。

2、这类重复问题通常要求保留重复记录中的第一条记录,操作方法如下

假设有重复的字段为Name,Address,要求得到这两个字段唯一的结果集
select identity(int,1,1) as autoID, * into #Tmp fromtableName

select min(autoID) as autoID into #Tmp2 from #Tmp group byName,autoID

select * from #Tmp where autoID in(select autoID from #tmp2)

最后一个select即得到了Name,Address不重复的结果集(但多了一个autoID字段,实际写时可以写在select子句中省去此列)

(四)
查询重复
select * from tablename where id in(
select id fromtablename 
group by id 
 having count(id) > 1 
)

sql将一个表中的数据插入到另一个表中

声名:a,b ,都是表 
--b表存在(两表结构一样) 
insert into b select * from a 

若两表只是有部分(字段)相同,则 
insert into b(col1,col2,col3,col4,...) select col1,col2,col3,col4,... from a where... 

把表a插入到表b中去--b表不存在 
select * into b from a 
or
select (字段1,字段2,...) into b from a 

在MySQL数据库添加和修改字段

1、登录数据库

mysql -u root -p 数据库名称

2、查询所有数据表

show tables;

2.1、 截断表

truncate table 表名; or truncate 表名;

2.2、 删除表

drop table 表名;

3、查询表的字段信息

desc 表名称;

3.1、 查看emp表格中的相关信息:

mysql> show full columns from emp;

4.1、添加表字段

alter table 表名称 add 字段名称 字段类型 [是否允许非空];

alter table table1 add transactor varchar(10) not Null;
alter table   table1 add id int unsigned not Null auto_increment primary key

4.2、修改某个表的字段类型及指定为空或非空

>alter table 表名称 change 字段名称 字段名称 字段类型 [是否允许非空];
>alter table 表名称 modify 字段名称 字段类型 [是否允许非空];

4.3、修改某个表的字段名称及指定为空或非空

>alter table 表名称 change 字段原名称 字段新名称 字段类型 [是否允许非空]

4.4、如果要删除某一字段,可用命令:

ALTER TABLE 表名 DROP 字段 名;

4.5、修改字段中的编码:

mysql> alter table 表名 convert to character set utf8 collate utf8_general_ci;

ERROR 1025 (HY000): Error on rename of ‘./test/#sql-27c_2308’ to ‘./test/student’ (errno: 150) 更改类型编码类型时 出现此错误一般为有外键约束 解决方法 暂时停止外键检查 set foreign_key_checks=0; 4.6

1.修改数据表名 
ALTER TABLE OLD_TABLE_NAME RENAME TO NEW_TABLE_NAME; 
2.修改列名 
ALTER TABLE TABLE_NAME RENAME COLUMN OLD_COLUMN_NAME TO NEW_COLUMN_NAME; 
3.修改列的数据类型 
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME NEW_DATATYPE; 
4.插入列 
ALTER TABLE TABLE_NAME ADD COLUMN_NAME DATATYPE; 
5.删除列 
ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;

5 、将两段sql语句连接起来用union all

select * from table 1

union all

select * from table2

6、SQL中的字母的大小写转换

  • 将大写字母改为小写字母
update 表名 set 字段名a= Lower(字段a)  
  • 将小写字母转化成大写字母
update 表名 set 字段名a= upper(字段名a) 

mysql获取某个表的所有字段名

mysql安装成功后可以看到已经存在mysqlinformation_schematest这个几个数据库,information_schema库中有一个名为COLUMNS的表,这个表中记录了数据库中所有表的字段信息。知道这个表后,获取任意表的字段就只需要一条select语句即可。例如:

select COLUMN_NAME from information_schema.COLUMNS
where table_name = 'your_table_name';

上述的做法有一点问题,如果多个数据库中存在你想要查询的表名,那么查询的结果会包括全部的字段信息。通过DESCinformation_schema.COLUMNS可以看到该表中列名为TABLE_SCHEMA是记录数据库名,因此下面的写法更为严格

select COLUMN_NAME from information_schema.COLUMNS
where table_name = 'your_table_name'
and table_schema = 'your_db_name';
#table_schema为数据库名,table_name是表名,
#获取数据库里所有表名
sql_table='SELECT table_name FROM information_schema.tables WHERE table_schema = "test" ORDER BY table_name DESC'

修改mysql字段大小写

# -*- coding;utf-8 -*-
import MySQLdb


dmdb_dbconn = MySQLdb.connect(host='192.168.8.30', user='root', passwd='', db='test', charset='utf8')
dmdb_cursor = dmdb_dbconn.cursor()

#table_schema为数据库名,table_name是表名,
#获取数据库里所有表名
sql_table='SELECT table_name FROM information_schema.tables WHERE table_schema = "test" ORDER BY table_name DESC'
#获取表里所有字段名和字段类型
sql_fields='select COLUMN_NAME,DATA_TYPE from information_schema.COLUMNS where table_name = %s%s%s and table_schema = "test"'
#更改字段大小写语句,因为类型包含关键字,取出来的类型是字符串,通过占位符匹配进去,运行会报错
sql_change='alter table %s change %s %s %s;'#(表名,原始字段名,新字段名,类型)

#修改字符集编码
# 'alter table 表名 convert to character set 字符集 collate 排序规则'
# 'alter table 表名 convert to character set utf8 collate utf8_general_ci'
dmdb_cursor.execute(sql_table)
tables = dmdb_cursor.fetchall()
# print(tables)
for table in tables:
    sql_field=sql_fields%('"',table[0],'"')
    dmdb_cursor.execute(sql_field)
    fileds = dmdb_cursor.fetchall()
    print(fileds)
    for filed in fileds:
        #将字段名转换为小写--lower(),大写---upper()
        #方法一:把所有执行语句写到一个文件中,在工具中执行所有sql语句
        sql_change_full=sql_change%(table[0],filed[0],str(filed[0]).lower(),filed[1])
        with open('sql_change.txt','a+') as f:
            f.write(sql_change_full+'n')

        #方法二
        upper_lower_change=str(filed[0]).lower()#转换为小写
        # upper_lower_change=str(filed[0]).upper()#转换为大写
        if filed[1]=='int':
            sql_change_type = 'alter table %s change %s %s int'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='varchar':
            sql_change_type = 'alter table %s change %s %s varchar'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='char':
            sql_change_type = 'alter table %s change %s %s char'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='datetime':
            sql_change_type = 'alter table %s change %s %s datetime'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='timestamp':
            sql_change_type = 'alter table %s change %s %s timestamp'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='bigint':
            sql_change_type = 'alter table %s change %s %s bigint'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='decimal':
            sql_change_type = 'alter table %s change %s %s decimal'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='double':
            sql_change_type = 'alter table %s change %s %s double'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='text':
            sql_change_type = 'alter table %s change %s %s text'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        elif filed[1]=='tinyint':
            sql_change_type = 'alter table %s change %s %s tinyint'
            dmdb_cursor.execute(sql_change_type%(table[0],filed[0],upper_lower_change))
            dmdb_dbconn.commit()
        else:
            print(filed[1],'不在所给的条件中,请添加条件')

参考: http://www.jb51.net/article/48363.htm https://www.server110.com/mariadb/201309/1849.html https://www.cnblogs.com/joy9707/p/8971684.html https://blog.csdn.net/w1025514023/article/details/53542634