经典SQL语句大全

合集下载

sql语句大全及用法 freebuf

sql语句大全及用法 freebuf

sql语句大全及用法 freebuf SQL(Structured Query Language)是一种用于管理关系型数据库的编程语言,它使用一系列指令来操作数据库。

下面是一些常用的SQL语句及其用法:1. SELECT:从数据库中检索数据。

用法:SELECT column1, column2, … FROM table_name;2. WHERE:过滤记录,执行条件查询。

用法:SELECT * FROM table_name WHERE column_name operator value;3. INSERT INTO:将新记录插入到表中。

用法:INSERT INTO table_name(column1, column2, …) VALUES(value1, value2, …);4. UPDATE:更新表中的记录。

用法:UPDATE table_name SET column_name = new_value WHERE column_name = value;5. DELETE:删除表中的记录。

用法:DELETE FROM table_name WHERE column_name = value;6. JOIN:在两个或多个表之间建立连接,并从中检索数据。

用法:SELECT * FROM table_name1 JOIN table_name2 ONtable_name1.column_name = table_name2.column_name;7. GROUP BY:根据一个或多个列对结果进行分组。

用法:SELECT column1, COUNT(column2) FROM table_name GROUP BY column1;8. ORDER BY:根据一个或多个列对结果进行排序。

用法:SELECT * FROM table_name ORDER BY column_nameASC/DESC;9. DISTINCT:返回不同的值,消除重复的行。

数据库sql查询语句大全

数据库sql查询语句大全

数据库sql查询语句大全数据库SQL查询语句是用来从数据库中检索数据的命令。

以下是一些常见的SQL查询语句大全:1. SELECT语句,用于从数据库中选择数据。

例如,SELECT FROM 表名;2. WHERE子句,用于过滤数据,只返回满足特定条件的行。

例如,SELECT FROM 表名 WHERE 列名 = '条件';3. ORDER BY子句,用于对结果集按照指定列进行排序。

例如,SELECT FROM 表名 ORDER BY 列名;4. GROUP BY子句,用于对结果集按照指定列进行分组。

例如,SELECT 列名1, 列名2 FROM 表名 GROUP BY 列名1;5. HAVING子句,用于过滤分组后的数据。

例如,SELECT 列名1, COUNT(列名2) FROM 表名 GROUP BY 列名1 HAVING COUNT(列名2) > 10;6. JOIN子句,用于在多个表之间建立关联。

例如,SELECT FROM 表名1 INNER JOIN 表名2 ON 表名1.列名 = 表名2.列名;7. UNION操作符,用于合并两个或多个SELECT语句的结果集。

例如,SELECT 列名1 FROM 表名1 UNION SELECT 列名2 FROM 表名2;8. INSERT INTO语句,用于向数据库表中插入新记录。

例如,INSERT INTO 表名 (列1, 列2) VALUES (值1, 值2);9. UPDATE语句,用于更新数据库表中的记录。

例如,UPDATE 表名 SET 列名 = 值 WHERE 条件;10. DELETE FROM语句,用于从数据库表中删除记录。

例如,DELETE FROM 表名 WHERE 条件;以上是一些常见的SQL查询语句,它们可以帮助用户从数据库中检索、过滤、排序、分组和更新数据。

当然,SQL语言还有很多其他的功能和语法,这些只是其中的一部分。

SQL语句大全

SQL语句大全

简单基本的sql语句(1) 数据记录筛选:sql="select * from 数据表 where 字段名=字段值 order by 字段名[desc]"sql="select * from 数据表 where 字段名 like '%字段值%' order by 字段名 [desc]"sql="select top 10 * from 数据表 where 字段名=字段值 order by 字段名 [desc]"sql="select top 10 * from 数据表 order by 字段名 [desc]"sql="select * from 数据表 where 字段名 in ('值1','值2','值3')"sql="select * from 数据表 where 字段名 between 值1 and 值2"(2) 更新数据记录:sql="update 数据表 set 字段名=字段值 where 条件表达式"sql="update 数据表 set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式"(3) 删除数据记录:sql="delete from 数据表 where 条件表达式"sql="delete from 数据表" (将数据表所有记录删除)(4) 添加数据记录:sql="insert into 数据表 (字段1,字段2,字段3 …) values (值1,值2,值3 …)"sql="insert into 目标数据表 select * from 源数据表" (把源数据表的记录添加到目标数据表)(5) 数据记录统计函数:AVG(字段名) 得出一个表格栏平均值COUNT(*;字段名) 对数据行数的统计或对某一栏有值的数据行数统计MAX(字段名) 取得一个表格栏最大的值MIN(字段名) 取得一个表格栏最小的值SUM(字段名) 把数据栏的值相加引用以上函数的方法:sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"set rs=conn.excute(sql)用 rs("别名") 获取统计的值,其它函数运用同上。

基础sql语句

基础sql语句

基础sql语句1. SELECT: 用于查询表中的数据,可以使用通配符(*)表示所有列或者指定列名。

例子:SELECT * FROM table_name;2. FROM: 用于指定查询的数据来源,即需要查询哪张表。

例子:SELECT * FROM table_name;3. WHERE: 用于筛选满足条件的数据行,可以使用比较运算符(>,<,=,!=,>=,<=)等。

例子:SELECT * FROM table_name WHEREcolumn_name >= 10;4. ORDER BY: 用于将查询结果按照某个列进行排序,可以指定升序或降序(ASC或DESC)。

例子:SELECT * FROM table_name ORDER BYcolumn_name ASC;5. GROUP BY: 用于将查询结果按照某个列进行分组,通常使用聚合函数(SUM,COUNT,AVG,MAX,MIN)进行数据计算。

例子:SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;6. LIMIT: 用于限制查询结果的数量,只返回前几条数据。

例子:SELECT * FROM table_name LIMIT 10;7. JOIN: 用于将多张表按照共同的字段进行连接,可以有多种连接方式(INNER JOIN,LEFT JOIN,RIGHT JOIN,FULL OUTER JOIN)。

例子:SELECT * FROM table1 LEFT JOIN table2 ONtable1.column_name = table2.column_name.。

sql经典查询语句

sql经典查询语句

sql经典查询语句查询:select * from table1 where ⼯资>2500 and ⼯资<3000 //查找⼀个⼯资区间select 姓名 from table1 where 性别='0' and ⼯资='4000' //查找性别和⼯资的条件select * from table1 where not ⼯资= 3200 //查找⼯资不等于3200的select * from table1 order by ⼯资desc //将⼯资按照降序排列select * from table1 order by ⼯资 asc //将⼯资按照升序排列select * from table1 where year(出⾝⽇期)=1987 //查询table1 中所有出⾝在1987的⼈select * from table1 where name like '%张' /'%张%' /'张%' //查询1,⾸位字‘张’3,尾位字‘张’2,模糊查询select * from table1 order by money desc //查询表1按照⼯资的降序排列表1 (升序为asc)select * from table1 where brithday is null //查询表1 中出⾝⽇期为空的⼈select * into table2 from table3 //将表3中的所有数据转换成表2 (相当于复制)删库和建库use 数据库(aa) //使⽤数据库aacreate bb(数据库) //创建数据库bbcreate table table3 ( name varchar(10),sex varchar(2),money money, brithday datetime) //创建⼀个表3中有姓名,性别,⼯资,出⾝⽇期(此表说明有四列)insert into table3 values ('张三','男','2500','1989-1-5') //在表中添加⼀⾏张三的记录alter table table3 add tilte varchar(10) //向表3 中添加⼀列“title(职位)”alter table table3 drop column sex //删除table3中‘性别’这⼀列drop database aa //删除数据库aadrop table table3 //删除表3delete * from table3 //删除table3 中所有的数据,但table3这个表还在delete from table1 where 姓名='倪涛' and ⽇期 is nulldelete from table1 where 姓名='倪涛' and ⽇期='1971'更改库表的数据update table3 set money=money*1.2 //为表3所有⼈⼯资都增长20%update table3 set money=money*1.2 where title='经理' //为表3中“职位”是经理的⼈⼯资增长20%update table1 set ⼯资= 5000 where 姓名='孙⼋' //将姓名为孙⼋的⼈的⼯资改为5000update table1 set 姓名='敬光' where 姓名='倪涛' and 性别=1 //将性别为男和姓名为倪涛的⼈改为敬光经典查询语句之⼆1显⽰系部编号为03的系部名称Select departname From department Where departno=’03’2.查询系部名称中含有'⼯程'两个字的系部的名称。

sql经典语句(SQLclassicsentences)

sql经典语句(SQLclassicsentences)

sql经典语句(SQL classic sentences)I. Basic operation1) DESC, the describe role is to display the structure of the data table using the form: desc data table name2) distinct eliminates duplicate data usage: select, distinct, field name, from data table3) order by field 1 ASC, field 2 desc4) nested queries select, emp.empno, emp.ename, emp.job, emp.salFrom scott.empWhere sal>= (select, Sal, from, scott.emp, where, ename='WARD');5) nested queries select, emp.empno, emp.ename, emp.job, in, emp.salFrom scott.empWhere, Sal, in (select, Sal, from, scott.emp, where, ename ='WARD');6) nested queries select, emp.empno, emp.ename, emp.job, any, emp.salFrom scott.empWhere Sal > any (select, Sal, from, scott.emp, where, job='MANAGER');Equivalent to (1) select, Sal, from, scott.emp, where, job ='MANAGER'(2) select, emp.empno, emp.ename, emp.job, emp.salFrom scott.empData found in where Sal > (1) data a, or, Sal > (1), data found in B, or, Sal > (1), CEg:Select, Sal, from, scott.emp, where, job ='MANAGER'results; 12,10,13Equivalent to sal=12,10,13 or SAL> (12, OR, 10, OR, 13)7) the intersection operation is the intersection concept in the set. The sum of the elements that belong to the set A and belongs to the set B is the intersection. In the command edit area, execute the following statement.Eg:(select, djbh, from, ck_rwd_hz) intersect (select, djbh, from, ck_rwd_mx) documents numbered the sameSelect * from ck_rwd_mx a,((select, djbh, from, ck_rwd_hz) intersect (select, djbh, from, ck_rwd_mx)) BWhere a.djbh =b.djbhTwo function1) ceil takes the minimum integer ceil (N) greater than or equal to the value N; select, Mgr, mgr/100, ceil (mgr/100), from, scott.emp;2) floor takes the maximum integer floor (N) less than or equal to the value N; select, Mgr, mgr/100, floor (mgr/100), from, scott.emp;3) the remainder of mod m divisible by mod (m, n) n4) power, m, N, square, mod (m, n)5) round m four, five, keep the n bit mod (m, n)Select round (8.655,2) from dual; 8.66Select round (8.653,2) from dual; 8.656) sign n>0, take 1; n=0, take 0; n<0, take -1;7) AVG averages AVG (field name)8) count statistics total count (field name) select (*) from scott.emp; select count (distinct job) from scott.emp;9) min calculates numeric fields minimum, select, min (SAL), minimum salary from scott.emp;10) max calculates numeric field maximum, select, max (SAL), highest salary from scott.emp;11) sum calculates the sum of numeric fields, select, sum (SAL), the sum of salaries, from, scott.emp;Three input data1) single data entryInsert into data tables (fields 1, fields 2,...) valuse (field name 1 values, field name 2 values,...)Numeric fields can write values directly; character fields add single quotation marks; date fields add single quotes; at the same time pay attention to the order of days and months2) multi line data entryInsert into data table (field name 1, field name 2,...)(select (field name 1 or operation, field name 2 or operation,...) from data table where condition)3) data replication between tablesCreate table scott.testAs(Select, distinct, empno, ename, hiredate, from, scott.emp, where, empno>=7000);Create table spkpk_liu as select * from spkfk; creates tables and copies data, but creates incomplete table informationThis is all the way to full table backups.Usually after the table is built, you need to see if you want to build the index and primary key again.And "create, table, spkpk_liu, as, select * from, spkfk.""After this table is built, many of the parameter values of the table are the default minimum values, such as the initial value of the original table 10M, and the new table is probably only 256K.Formal environment used in the table, generally do not recommend such a table built.In this way, just a little lazy, if you do so,A statement can achieve the purpose of building tables and inserting data.For example, you need to modify the data in table A, and you might want to back up the data from the A table before you modify it.This time you can use create table... As...This makes it easy to retrieve data from the A table in the futureYou can do this when you debug your own program, but you can't create processes, packages, functions like thisFour delete dataDelete deletes data; truncate deletes the entire table data, but retains the structure1) delete recordsDelete from scott.test where empno and empno <=8000 > = 7500;2) delete the entire dataTruncate table scott.test;Similarities and differences between truncate, delete and dropNote: the delete here refers to the delete statement without the where clauseThe same thing: truncate and the delete without the where clause, and drop will delete the data in the tableDifference:1. truncate and delete only delete data and do not delete the structure of the table (definition)The drop statement will delete the structure of the table, the dependent constraints (constrain), the trigger, and the index (index); the stored procedure / function that depends on the table will be retained, but the invalid state will be changedThe 2.delete statement is DML, which is put into the rollback segement before the transaction is committed, and if you have the corresponding trigger, the execution will be triggeredTruncate, drop is DDL, the operation takes effect immediately, and the original data is not put into the rollback segment and cannot be rolled back. The operation does not trigger trigger.. Obviously, the drop statement releases all the space occupied by the table3. speed, in general: drop>, truncate > deleteOn use, you want to delete part of the data rows, with delete,take care to bring the where clause. The rollback section is large enough to be rolled back through the ROBACK, and there is considerable room for recoveryTo delete tables, of course, use dropYou want to keep the table and delete all the data. If you have nothing to do with the transaction, you can use truncate. Truncate, table, XX, delete the entire table of data, there is no room for recovery, the benefits can be arranged in the table debris, release spaceSo it's better to back up the data firstIf you are tidying up the inner fragments of a table, you can use truncate to catch up with reuse stroage and then import / insert data againFive update dataUpdate data sheetSet field name, 1=, new assignment, field name, 2=, new assignment,...Where conditionUpdate scott.empSet, empno=8888, ename='TOM', hiredate='03-9, -2002'Where empno = 7566;Update scott.empSet sal=(select, sal+300, from, scott.emp, where, empno = 8099)Where empno=8099;Decode (condition, value 1, translation value 1, value 2, translation value 2, value n, translation value n, default value)Six data export1 export the database TEST completely, export the user name system password manager to D:\daochu.dmpExpsystem/manager@TESTfile=d:\daochu.dmp full=y2 export the system user in the database to the table of the sys userExpsystem/manager@TESTfile=d:\daochu.dmp only wner= (system, Sys)3 export tables table1 and table2 from the databaseExpsystem/manager@TESTfile=d:\daochu.dmp tables= (table1, table2)4 export the field filed1 in the table table1 in the database to data that starts with "00"Expsystem/manager@TESTfile=d:\daochu.dmp tables= (table1) query=\ "where filed1 like'00%'\""Explmis_wh/lmis@lmisbuffer=10000 only WNER=lmis_wh rows=nfile=d:\lmis_wh_nodata.dmp log=d:\lmis_wh_nodata.logImplmis/lmis@lmisbuffer=10000, fromuser=lmis_wh, touser=lmis, file=d:\lmis_wh_nodata.dmp, log=d:\lmis_wh_nodata.logC:\>implmis/lmis@lmisbuffer=50000000, full=n,file=e:\daochu.dmp, ignore=y, rows=yCommit=y compile=y fromuser=lmis_wh touser=lmisSeven data import1 import data from the D:\daochu.dmp into the TEST database.Impsystem/manager@TEST file=d:\daochu.dmpThere may be a problem with it because some tables already exist, and then it is reported wrong, and the table is not imported.It's OK to add ignore=y at the back.2 import table table1 from d:\daochu.dmpImpsystem/manager@TEST file=d:\daochu.dmp tables= (table1)SQL definition: SQL is a database oriented general data processing language specification, can complete the following functions: data extraction query, insert modify delete data generation, modify and delete database objects, database security, database integrity control and data protection.SQL classification:DDL - Data Definition Language (CREATE, ALTER, DROP, DECLARE)DML - Data Manipulation Language (SELECT, DELETE, UPDATE, INSERT)DCL - data control language (GRANT, REVOKE, COMMIT, ROLLBACK) DDL - database definition language: direct submission. CREATE: used to create database objects.DECLARE: in addition to creating temporary tables that are used only during the process, the DECLARE statements are very similar to the CREATE statements. The only object that can be declared is the table. And must be added to the user temporary tablespace.DROP: you can delete any object created with CREATE (database object) and DECLARE (table).ALTER: allows you to modify information about certain databaseobjects. Cannot modify index.Eight, the following is mainly based on object presentation of basic grammar1, database:Create database: CREATE, DATABASE, database-name, [USING, CODESET, codeset, TERRITORY, territory]Note: the code page problem.Delete database: drop, database, dbname2, table:Create new table:Create, table, tabname (col1, Type1, [not, null], [primary, key], col2, type2, [not, null],...)Create a new table based on the existing table:A:create, table, tab_new, like, tab_oldB:create, table, tab_new, as, select, col1, col2... From tab_old definition onlyModify table:Add a column:Alter, table, tabname, add, column, col, typeNote: column added will not be deleted. The DB2 column after the data type does not change, the only change is to increase the size of the varchar. Add primary key:Alter, table, tabname, add, primary, key (Col)Delete Primary key:Alter, table, tabname, drop, primary, key (Col)Delete table: drop, table, tabnameAlter table BMDOC_LIUFDrop constraint PK1_BMDOC cascade;3, table space:Create table spaces: create, tablespace, tbsname, PageSize, 4K, managed, by, database, using (file, file, size)Adding containers to tablespace: alter, tablespace, tablespace_name, add (file,'filename', size)Note: the operation is irreversible and will not be removed after adding the container. Therefore, when it is added, pay attention to it.Delete tablespace: drop, tablespace, tbsname4, index:Create indexes: create, [unique], index, idxname, on, tabname (col... ).Delete index: drop, index, idxnameNote: the index is not modifiable. If you want to change it, you must delete it.5 views:Create views: create, view, VIEWNAME, as, select, statementDelete view: drop view VIEWNAMENote: the only change to the view is the reference type column, which changes the range of columns. None of the other definitions can be modified. The view becomes invalid when the view is based on the base table drop.DML - the database manipulation language, which does not implicitly submit the current transaction and is committed to the setting of the visual environment.SELECT: querying data from tablesNote: the connection in the condition avoids Cartesian productDELETE: delete data from existing tablesUPDATE: update data for existing tablesINSERT: insert data into existing tablesNote: whether DELETE, UPDATE, and INSERT are submitted directly depends on the environment in which the statement is executed.Pay attention to the full transaction log when executing.2, DELETE: delete records from the tableSyntax format:DELETE, FROM, tablename, WHERE (conditions)3, INSERT: insert a record into the tableSyntax format:INSERT INTO tablename (col1, col2),... ) VALUES (value1, Value2),... );INSERT INTO tablename (col1, col2),... ) VALUES (value1, Value2),... ) (value1, value2,... ),......Insert does not wait for any program and does not cause locking4, UPDATE:Syntax format:UPDATE tabname SET (col1=values1, col2=values2),... (WHERE) (conditions);Note: update is slower and requires indexing on the corresponding column.Nine permissionsDCL - Data Control LanguageGRANT - Grant user permissionsREVOKE - revoke user rightsCOMMIT - commit transactions can permanently modify the databaseROLLBACK - rollback transactions, eliminating all changes made after the last COMMIT command, so that the contents of the database are restored to the state after the last COMMIT execution.1, GRANT: all or administrators assign access rights to other usersSyntax format:Grant [all privileges|privileges,... On tabname VIEWNAME to [public|user |,... .2 and REVOKE: cancel one of the user's access rightsSyntax format:Revoke [all privileges|privileges,... On tabname VIEWNAME from [public|user |,... .Note: any permissions of users of instance level cannot be canceled. They are not authorized by grant, but are permissions implemented by groups.3, COMMIT: permanently records changes made in the transaction to the database.Syntax format:Commit [work]4, ROLLBACK: will undo all changes made since the last submission.Syntax format:Rollback [work]Ten advanced SQL brief introductionFirst, the query between the use of computing wordsA:UNION operatorThe UNION operator derives a result table by combining two other result tables (such as TABLE1 and TABLE2) and eliminating any duplicate rows in the table.When ALL is used with UNION (that is, UNION ALL), the duplicate rows are not eliminated. In the two case, each row of the derived table does not come from TABLE1, or from TABLE2.B:EXCEPT operatorThe EXCEPT operator derives a result table by including all rows in TABLE1, but not in TABLE2, and eliminating all duplicate rows. When ALL is used with EXCEPT (EXCEPT ALL), the duplicate rows are not eliminated.C:INTERSECT operatorThe INTERSECT operator derives a result table by including only rows in TABLE1 and TABLE2 and eliminating all duplicate rows. When ALL is used with INTERSECT (INTERSECT ALL), the duplicate rows are not eliminated.Note: several query results lines using arithmetic words must be consistent.Appendix: introduction to commonly used functions1, type conversion function:Converted to a numeric type:Decimal, double, Integer, smallint, realHex (ARG): 16 hexadecimal representation converted into parameters.Converted to string type:Char, varcharDigits (ARG): returns the string representation of Arg, and Arg must be decimal.Converted to date or time:Date, time, timestamp2, time and date:Year, quarter, month, week, day, hour, minute, secondDayofyear (ARG): returns the daily value of Arg in the yearDayofweek (ARG): returns the daily value of Arg in the weekDays (ARG): the integer representation of the return date, the number of days from the 0001-01-01.Midnight_seconds (ARG): the number of seconds between midnight and arg.Monthname (ARG): returns the month name of arg.Dayname (ARG): the week that returns arg.3 string function:Length, lcase, ucase, ltrim, rtrimCoalesce (arg1, arg2)... ) returns the first non null parameter in the argument set.Concat (arg1, arg2): connect two strings, arg1 and arg2.Insert (arg1, POS, size, arg2): returns a arg1 that removes size characters from POS and inserts arg2 into that location.Left (Arg, length): returns the leftmost length string of arg.Locate (arg1, arg2, &lt, pos>): find the location of the first occurrence of arg1 in arg2, specify POS, and start looking for the location of the arg1 from the POS of arg2.Posstr (arg1, arg2): returns the position where arg2 first appeared in arg1.Repeat (arg1, num_times): returns the string arg1 repeated num_times times.Replace (arg1, arg2, ARG3): replace all arg2 in arg1 to arg3.Right (Arg, length): returns a string consisting of lengthbytes on the left of the arg.Space (ARG): returns a string containing Arg spaces.Substr (arg1, POS, &lt, length>): returns the length character at the start of the POS position in arg1, and returns the remaining characters if no length is specified.4. Mathematical function:Abs, count, Max, min, sumCeil (ARG): returns the smallest integer greater than or equal to arg.Floor (ARG): returns the smallest integer less than or equal to the parameter.Mod (arg1,Arg2) returns arg1 by the remainder of the arg2, with the same symbol as arg1.Rand (): returns a random number between 1 and 1.Power (arg1, arg2): returns the arg2 power of arg1.Round (arg1, arg2): four, five into the truncated processing, arg2 is the number of bits, if arg2 is negative, then the number of decimal points before four to five processing.Sigh (ARG): symbolic designator to return arg. -1,0,1 representation.Truncate (arg1, arg2): truncate arg1, arg2 is the number of digits, and if arg2 is negative, keep the arg2 bits before the arg1 decimal point.5, others:Nullif (arg1, arg2): returns if the 2 arguments are equal, otherwise the argument 1 is returned。

经典SQL语句大全(超全)

经典SQL语句大全(超全)

一、基础1、说明:创建数据库CREATE DATABASE database-name2、说明:删除数据库drop database dbname3、说明:备份sql server--- 创建备份数据的 deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1. dat'--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)根据已有的表创建新表:A:create table tab_new like tab_old (使用旧表创建新表)B:create table tab_new as select col1,col2… from tab_old definition only5、说明:删除新表drop table tabname6、说明:增加一个列Alter table tabname add column col type注:列增加后将不能删除。

DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。

7、说明:添加主键:Alter table tabname add primary key(col)说明:删除主键: Alter table tabname drop primary key(col)8、说明:创建索引:create [unique] index idxname on tabname(col….) 删除索引:drop index idxname注:索引是不可更改的,想更改必须删除重新建。

9、说明:创建视图:create view viewname as select statement删除视图:drop view viewname10、说明:几个简单的基本的sql语句选择:select * from table1 where 范围插入:insert into table1(field1,field2) values(value1,value2)删除:delete from table1 where 范围更新:update table1 set field1=value1 where 范围查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!排序:select * from table1 order by field1,field2 [desc]总数:select count as totalcount from table1求和:select sum(field1) as sumvalue from table1平均:select avg(field1) as avgvalue from table1最大:select max(field1) as maxvalue from table1最小:select min(field1) as minvalue from table111、说明:几个高级查询运算词A:UNION 运算符UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。

sql简单语句

sql简单语句

sql简单语句
SQL(StructuredQueryLanguage)是一种用于数据库管理的编程语言,它可以用于创建、读取、更新和删除数据库中的数据。

以下是一些常用的 SQL 简单语句:
1. SELECT:用于从数据库中读取数据。

例如:SELECT * FROM 表名;
2. INSERT:用于向数据库中插入数据。

例如:INSERT INTO 表名(字段1, 字段2, ...) VALUES (值1, 值2, ...);
3. UPDATE:用于更新数据库中的数据。

例如:UPDATE 表名 SET 字段1 = 值1, 字段2 = 值2 WHERE 条件;
4. DELETE:用于删除数据库中的数据。

例如:DELETE FROM 表名 WHERE 条件;
5. CREATE:用于创建数据库或表。

例如:CREATE DATABASE 数据库名;
CREATE TABLE 表名 (字段1 数据类型1, 字段2 数据类型
2, ...);
6. DROP:用于删除数据库或表。

例如:DROP DATABASE 数据库名;
DROP TABLE 表名;
以上是 SQL 简单语句中的一部分,它们是使用 SQL 进行数据库
管理时必须掌握的基础知识。

sql经典50题建表语句

sql经典50题建表语句

sql经典50题建表语句1、题目:创建一个名为"employees"的表,包含"id"、"name"和"salary"三个字段。

sql:CREATE TABLE employees (id INT PRIMARY KEY,name VARCHAR(50),salary DECIMAL(10, 2));2、题目:创建一个名为"orders"的表,包含"order_id"、"customer_id"和"order_date"三个字段。

sql:CREATE TABLE orders (order_id INT PRIMARY KEY,customer_id INT,order_date DATE);3、题目:创建一个名为"products"的表,包含"product_id"、"product_name"和"price"三个字段。

sql:CREATE TABLE products (product_id INT PRIMARY KEY,product_name VARCHAR(50),price DECIMAL(10, 2));4、题目:创建一个名为"customers"的表,包含"customer_id"、"first_name"、"last_name"和"email"四个字段。

sql:CREATE TABLE customers (customer_id INT PRIMARY KEY,first_name VARCHAR(50),last_name VARCHAR(50),email VARCHAR(100));5、题目:创建一个名为"addresses"的表,包含"address_id"、"street"、"city"和"state"四个字段。

sql语句大全(详细)

sql语句大全(详细)

sql语句大全(详细)sql语句大全(详细)数据库操作1.查看所有数据库show databases;2.查看当前使用的数据库select database();3.创建数据库create databases 数据库名 charset=utf8;4.删除数据库drop database 数据库名5.使用数据句库use database 数据库名6.查看数据库中所有表show tables;表的操作1.查看表结构desc 表名2.创建表结构的语法create table table_name(字段名数据类型可选的约束条件);demo:创建班级和学生表create table classes(id int unsigned auto_increment primary key not null, name varchar(10));create table students(id int unsigned primary key auto_increment not null, name varchar(20) default '',age tinyint unsigned default 0,height decimal(5,2),gender enum('男','女','人妖','保密'),cls_id int unsigned default 0)3.修改表–添加字段alter table 表名 add 列名类型demo:alter table students add birthday datetime;4.修改表–修改字段–重命名版alert table 表名 change 原名新名类型及约束demo:alter table syudents change birthday birth datetime not null;5.修改表–修改字段–不重命名alter table 表名 modify 列名类型及约束demo : alter table students modify birth date nout noll;6.删除表–删除字段alter table 表名 drop 列名demo :later table students drop birthday;7.删除表drop table 表名demo:drop table students;8.查看表的创建语句–详细过程show create table 表名demo : show create tabele students;查询基本使用1.查询所有列select * from 表名例:select * from classes;2.查询指定列select 列1,列2,...from 表名;例:select id,name from classes;增加说明:主键列是自动增长,但是在全列插入时需要占位,通常使用空值(0或者null) ; 字段默认值 default 来占位,插入成功后以实际数据为准1.全列插入:值的顺序与表结构字段的顺序完全一一对应此时字段名列表不用填写insert into 表名 values (...)例:insert into students values(0,’郭靖',1,'蒙古','2016-1-2');2.部分列插入:值的顺序与给出的列顺序对应此时需要根据实际的数据的特点填写对应字段列表insert into 表名 (列1,...) values(值1,...)例:insert into students(name,hometown,birthday) values('黄蓉','桃花岛','2016-3-2');上面的语句一次可以向表中插入一行数据,还可以一次性插入多行数据,这样可以减少与数据库的通信3.全列多行插入insert into 表名 values(...),(...)...;例:insert into classes values(0,'python1'),(0,'python2');4.部分列多行插入insert into 表名(列1,...) values(值1,...),(值1,...)...;例:insert into students(name) values('杨康'),('杨过'),('小龙女');修改update 表名 set 列1=值1,列2=值2... where 条件例:update students set gender=0,hometown='北京' where id=5;删除delete from 表名 where 条件例:delete from students where id=5;逻辑删除,本质就是修改操作update students set isdelete=1 where id=1;as关键字1.使用 as 给字段起别名select id as 序号, name as 名字, gender as 性别 from students;2.可以通过 as 给表起别名select s.id,,s.gender from students as s;条件语句查询where后面支持多种运算符,进行条件的处理比较运算符逻辑运算符模糊查询范围查询空判断比较运算符等于: =大于: >大于等于: >=小于等于: <=不等于: != 或 <>例1:查询编号大于3的学生select * from students where id > 3;例2:查询编号不大于4的学生select * from students where id <= 4;例3:查询姓名不是“黄蓉”的学生select * from students where name != '黄蓉';例4:查询没被删除的学生select * from students where is_delete=0;逻辑运算符andornot例5:查询编号大于3的女同学select * from students where id > 3 and gender=0;例6:查询编号小于4或没被删除的学生select * from students where id < 4 or is_delete=0;模糊查询like%表示任意多个任意字符_表示一个任意字符例7:查询姓黄的学生select * from students where name like '黄%';例8:查询姓黄并且“名”是一个字的学生select * from students where name like '黄_';例9:查询姓黄或叫靖的学生select * from students where name like '黄%' or name like '%靖';范围查询分为连续范围查询和非连续范围查询in表示在一个非连续的范围内例10:查询编号是1或3或8的学生select * from students where id in(1,3,8);between … and …表示在一个连续的范围内例11:查询编号为3至8的学生select * from students where id between 3 and 8;例12:查询编号是3至8的男生select * from students where (id between 3 and 8) and gender=1;空判断判断为空例13:查询没有填写身高的学生select * from students where height is null;注意: 1. null与’'是不同的 2. is null判非空is not null例14:查询填写了身高的学生select * from students where height is not null;例15:查询填写了身高的男生select * from students where height is not null and gender=1;优先级优先级由高到低的顺序为:小括号,not,比较运算符,逻辑运算符and比or先运算,如果同时出现并希望先算or,需要结合()使用排序排序查询语法:select * from 表名 order by 列1 asc|desc [,列2 asc|desc,...]语法说明:将行数据按照列1进行排序,如果某些行列1 的值相同时,则按照列2 排序,以此类推asc从小到大排列,即升序desc从大到小排序,即降序默认按照列值从小到大排列(即asc关键字)例1:查询未删除男生信息,按学号降序select * from students where gender=1 and is_delete=0 order by id desc;例2:查询未删除学生信息,按名称升序select * from students where is_delete=0 order by name;例3:显示所有的学生信息,先按照年龄从大–>小排序,当年龄相同时按照身高从高–>矮排序select * from students order by age desc,height desc;分页select * from 表名 limit start=0,count说明从start开始,获取count条数据start默认值为0也就是当用户需要获取数据的前n条的时候可以直接写上xxx limit n;例1:查询前3行男生信息select * from students where gender=1 limit 0,3;关于分页的一个有趣的推导公式已知:每页显示m条数据,当前显示第n页求总页数:此段逻辑后面会在python项目中实现查询总条数p1使用p1除以m得到p2如果整除则p2为总数页如果不整除则p2+1为总页数获取第n页的数据的SQL语句求解思路第n页前有n-1页所在第n页前已经显示的数据的总量是(n-1)*m由于数据的下标从0开始所以第n页前所有的网页的下标是0,1,…,(n-1)*m-1所以第n页的数据起始下标是(n-1)*m获取第n页数据的SQL语句select * from students where is_delete=0 limit (n-1)*m,m注意:在sql语句中limit后不可以直接加公式聚合函数总数count(*) 表示计算总行数,括号中写星与列名,结果是相同的例1:查询学生总数select count(*) from students;最大值max(列) 表示求此列的最大值例2:查询女生的编号最大值select max(id) from students where gender=2;最小值min(列) 表示求此列的最小值例3:查询未删除的学生最小编号select min(id) from students where is_delete=0;求和sum(列) 表示求此列的和例4:查询男生的总年龄select sum(age) from students where gender=1;–平均年龄select sum(age)/count(*) from students where gender=1;平均值avg(列) 表示求此列的平均值例5:查询未删除女生的编号平均值select avg(id) from students where is_delete=0 andgender=2;分组group bygroup by + group_concat()group_concat(字段名)根据分组结果,使用group_concat()来放置每一个分组中某字段的集合group by + 聚合函数通过group_concat()的启发,我们既然可以统计出每个分组的某字段的值的集合,那么我们也可以通过集合函数来对这个值的集合做一些操作group by + havinghaving 条件表达式:用来过滤分组结果having作用和where类似,但having只能用于group by 而where是用来过滤表数据group by + with rollupwith rollup的作用是:在最后新增一行,来记录当前表中该字段对应的操作结果,一般是汇总结果。

SQL语句大全大全(经典珍藏版)

SQL语句大全大全(经典珍藏版)

SQL语句大全--语句功能--数据操作SELECT --从数据库表中检索数据行和列INSERT --向数据库表添加新数据行DELETE --从数据库表中删除数据行UPDATE --更新数据库表中的数据-数据定义CREATE TABLE --创建一个数据库表DROP TABLE --从数据库中删除表ALTER TABLE --修改数据库表结构CREATE VIEW --创建一个视图DROP VIEW --从数据库中删除视图CREATE INDEX --为数据库表创建一个索引DROP INDEX --从数据库中删除索引CREATE PROCEDURE --创建一个存储过程DROP PROCEDURE --从数据库中删除存储过程CREATE TRIGGER --创建一个触发器DROP TRIGGER --从数据库中删除触发器CREATE SCHEMA --向数据库添加一个新模式DROP SCHEMA --从数据库中删除一个模式CREATE DOMAIN --创建一个数据值域ALTER DOMAIN --改变域定义DROP DOMAIN --从数据库中删除一个域--数据控制GRANT --授予用户访问权限DENY --拒绝用户访问REVOKE --解除用户访问权限--事务控制COMMIT --结束当前事务ROLLBACK --中止当前事务SET TRANSACTION --定义当前事务数据访问特征--程序化SQLDECLARE --为查询设定游标EXPLAN --为查询描述数据访问计划OPEN --检索查询结果打开一个游标FETCH --检索一行查询结果CLOSE --关闭游标PREPARE --为动态执行准备SQL 语句EXECUTE --动态地执行SQL 语句DESCRIBE --描述准备好的查询---局部变量declare @id char(10)--set @id = '10010001'select @id = '10010001'---全局变量---必须以@@开头--IF ELSEdeclare @x int @y int @z intselect @x = 1 @y = 2 @z=3if @x > @yprint 'x > y' --打印字符串'x > y'else if @y > @zprint 'y > z'else print 'z > y'--CASEuse panguupdate employeeset e_wage =casewhen job_level = ‟1‟ then e_wage*1.08 when job_level = ‟2‟ then e_wage*1.07 when job_level = ‟3‟ then e_wage*1.06 else e_wage*1.05end--WHILE CONTINUE BREAK declare @x int @y int @c intselect @x = 1 @y=1while @x < 3beginprint @x --打印变量x 的值while @y < 3beginselect @c = 100*@x + @yprint @c --打印变量c 的值select @y = @y + 1endselect @x = @x + 1select @y = 1end--WAITFOR--例等待1 小时2 分零3 秒后才执行SELECT 语句wai tfor delay ‟01:02:03‟select * from employee--例等到晚上11 点零8 分后才执行SELECT 语句waitfor time ‟23:08:00‟select * from employee***SELECT***select *(列名) from table_name(表名) where column_name operator value ex:(宿主)select * from stock_information where stockid = str(nid)stockname = 'str_name'stockname like '% find this %'stockname like '[a-zA-Z]%' --------- ([]指定值的范围)stockname like '[^F-M]%' --------- (^排除指定范围)--------- 只能在使用like关键字的where子句中使用通配符)or stockpath = 'stock_path'or stocknumber < 1000and stockindex = 24not stock*** = 'man'stocknumber between 20 and 100stocknumber in(10,20,30)order by stockid desc(asc) --------- 排序,desc-降序,asc-升序order by 1,2 --------- by列号stockname = (select stockname from stock_information where stockid = 4)--------- 子查询--------- 除非能确保内层select只返回一个行的值,--------- 否则应在外层where子句中用一个in限定符select distinct column_name form table_name --------- distinct指定检索独有的列值,不重复select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_name select stockname , "stocknumber" = count(*) from table_name group by stockname--------- group by 将表按行分组,指定列中有相同的值having count(*) = 2 --------- having选定指定的组select *from table1, table2where table1.id *= table2.id -------- 左外部连接,table1中有的而table2中没有得以null表示table1.id =* table2.id -------- 右外部连接select stockname from table1union [all] ----- union合并查询结果集,all-保留重复行select stockname from table2***insert***insert into table_name (Stock_name,Stock_number) value ("xxx","xxxx")value (select Stockname , Stocknumber from Stock_table2)---value为select语句***update***update table_name set Stockname = "xxx" [where Stockid = 3]Stockname = defaultStockname = nullStocknumber = Stockname + 4***delete***delete from table_name where Stockid = 3truncate table_name ----------- 删除表中所有行,仍保持表的完整性drop table table_name --------------- 完全删除表***alter table*** --- 修改数据库表结构alter table database.owner.table_name add column_name char(2) null .....sp_help table_name ---- 显示表已有特征create table table_name (name char(20), age smallint, lname varchar(30))insert into table_name select ......... ----- 实现删除列的方法(创建新表)alter table table_name drop constraint Stockname_default ---- 删除Stockname的default约束***function(/*常用函数*/)***----统计函数----AVG --求平均值COUNT --统计数目MAX --求最大值MIN --求最小值SUM --求和--AVGuse panguselect avg(e_wage) as dept_avgWagefrom employeegroup by dept_id--MAX--求工资最高的员工姓名use panguselect e_namefrom employeewhere e_wage =(select max(e_wage)from employee)--STDEV()--STDEV()函数返回表达式中所有数据的标准差--STDEVP()--STDEVP()函数返回总体标准差--VAR()--VAR()函数返回表达式中所有值的统计变异数--VARP()--VARP()函数返回总体变异数----算术函数----/***三角函数***/SIN(float_expression) --返回以弧度表示的角的正弦COS(float_expression) --返回以弧度表示的角的余弦TAN(float_expression) --返回以弧度表示的角的正切COT(float_expression) --返回以弧度表示的角的余切/***反三角函数***/ASIN(float_expression) --返回正弦是FLOAT 值的以弧度表示的角ACOS(float_expression) --返回余弦是FLOAT 值的以弧度表示的角ATAN(float_expression) --返回正切是FLOAT 值的以弧度表示的角ATAN2(float_expression1,float_expression2)--返回正切是float_expression1 /float_expres-sion2的以弧度表示的角DEGREES(numeric_expression)--把弧度转换为角度返回与表达式相同的数据类型可为--INTEGER/MONEY/REAL/FLOAT 类型RADIANS(numeric_expression) --把角度转换为弧度返回与表达式相同的数据类型可为--INTEGER/MONEY/REAL/FLOAT 类型EXP(float_expression) --返回表达式的指数值LOG(float_expression) --返回表达式的自然对数值LOG10(float_expression)--返回表达式的以10 为底的对数值SQRT(float_expression) --返回表达式的平方根/***取近似值函数***/CEILING(numeric_expression) --返回>=表达式的最小整数返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型FLOOR(numeric_expression) --返回<=表达式的最小整数返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型ROUND(numeric_expression) --返回以integer_expression 为精度的四舍五入值返回的数据--类型与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型ABS(numeric_expression) --返回表达式的绝对值返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型SIGN(numeric_expression) --测试参数的正负号返回0 零值1 正数或-1 负数返回的数据类型--与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型PI() --返回值为π 即3.1415926535897936RAND([integer_expression]) --用任选的[integer_expression]做种子值得出0-1 间的随机浮点数----字符串函数----ASCII() --函数返回字符表达式最左端字符的ASCII 码值CHAR() --函数用于将ASCII 码转换为字符--如果没有输入0 ~ 255 之间的ASCII 码值CHAR 函数会返回一个NULL 值LOWER() --函数把字符串全部转换为小写UPPER() --函数把字符串全部转换为大写STR() --函数把数值型数据转换为字符型数据LTRIM() --函数把字符串头部的空格去掉RTRIM() --函数把字符串尾部的空格去掉LEFT(),RIGHT(),SUBSTRING() --函数返回部分字符串CHARINDEX(),PATINDEX() --函数返回字符串中某个指定的子串出现的开始位置SOUNDEX() --函数返回一个四位字符码--SOUNDEX函数可用来查找声音相似的字符串但SOUNDEX函数对数字和汉字均只返回0 值DIFFERENCE() --函数返回由SOUNDEX 函数返回的两个字符表达式的值的差异--0 两个SOUNDEX 函数返回值的第一个字符不同--1 两个SOUNDEX 函数返回值的第一个字符相同--2 两个SOUNDEX 函数返回值的第一二个字符相同--3 两个SOUNDEX 函数返回值的第一二三个字符相同--4 两个SOUNDEX 函数返回值完全相同QUOTENAME() --函数返回被特定字符括起来的字符串/*select quotename('abc', '{') quotename('abc')运行结果如下----------------------------------{{abc} [abc]*/REPLICATE() --函数返回一个重复character_expression 指定次数的字符串/*select replicate('abc', 3) replicate( 'abc', -2)运行结果如下----------- -----------abcabcabc NULL*/REVERSE() --函数将指定的字符串的字符排列顺序颠倒REPLACE() --函数返回被替换了指定子串的字符串/*select replace('abc123g', '123', 'def')运行结果如下----------- -----------abcdefg*/SPACE() --函数返回一个有指定长度的空白字符串STUFF() --函数用另一子串替换字符串指定位置长度的子串----数据类型转换函数----CAST() 函数语法如下CAST() (<expression> AS <data_ type>[ length ])CONVERT() 函数语法如下CONVERT() (<data_ type>[ length ], <expression> [, style])select cast(100+99 as char) convert(varchar(12), getdate())运行结果如下------------------------------ ------------199 Jan 15 2000----日期函数----DAY() --函数返回date_expression 中的日期值MONTH() --函数返回date_expression 中的月份值YEAR() --函数返回date_expression 中的年份值DATEADD(<datepart> ,<number> ,<date>)--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期DATEDIFF(<datepart> ,<number> ,<date>)--函数返回两个指定日期在datepart 方面的不同之处DATENAME(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分DATEPART(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分GETDATE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间----系统函数----APP_NAME() --函数返回当前执行的应用程序的名称COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值COL_LENGTH(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值COL_NAME(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名DATALENGTH() --函数返回数据表达式的数据的实际长度DB_ID(['database_name']) --函数返回数据库的编号DB_NAME(database_id) --函数返回数据库的名称HOST_ID() --函数返回服务器端计算机的名称HOST_NAME() --函数返回服务器端计算机的名称IDENTITY(<data_type>[, seed increment]) [AS column_name])--IDENTITY() 函数只在SELECT INTO 语句中使用用于插入一个identity column列到新表中/*select identity(int, 1, 1) as column_nameinto newtablefrom oldtable*/ISDATE() --函数判断所给定的表达式是否为合理日期ISNULL(<check_expression>, <replacement_value>) --函数将表达式中的NULL 值用指定值替换ISNUMERIC() --函数判断所给定的表达式是否为合理的数值NEWID() --函数返回一个UNIQUEIDENTIFIER 类型的数值NULLIF(<expression1>, <expression2>)--NULLIF 函数在expression1 与expression2 相等时返回NULL 值若不相等时则返回expression1 的值sql中的保留字action add aggregate allalter after and asasc avg avg_row_length auto_incrementbetween bigint bit binaryblob bool both bycascade case char characterchange check checksum columncolumns comment constraint createcross current_date current_time current_timestampdata database databases datedatetime day day_hour day_minuteday_second dayofmonth dayofweek dayofyeardec decimal default delayeddelay_key_write delete desc describedistinct distinctrow double dropend else escape escapedenclosed enum explain existsfields file first floatfloat4 float8 flush foreignfrom for full functionglobal grant grants grouphaving heap high_priority hourhour_minute hour_second hosts identifiedignore in index infileinner insert insert_id intinteger interval int1 int2int3 int4 int8 intoif is isam joinkey keys kill last_insert_idleading left length likelines limit load locallock logs long longbloblongtext low_priority max max_rowsmatch mediumblob mediumtext mediumintmiddleint min_rows minute minute_secondmodify month monthname myisamnatural numeric no notnull on optimize optionoptionally or order outeroutfile pack_keys partial passwordprecision primary procedure processprocesslist privileges read realreferences reload regexp renamereplace restrict returns revokerlike row rows secondselect set show shutdownsmallint soname sql_big_tables sql_big_selectssql_low_priority_updates sql_log_off sql_log_update sql_select_limit sql_small_result sql_big_result sql_warnings straight_joinstarting status string tabletables temporary terminated textthen time timestamp tinyblobtinytext tinyint trailing totype use using uniqueunlock unsigned update usagevalues varchar variables varyingvarbinary with write whenwhere year year_month zerofill查看全文常用SQL命令和ASP编程在进行数据库操作时,无非就是添加、删除、修改,这得设计到一些常用的SQL 语句,如下:SQL常用命令使用方法:(1) 数据记录筛选:sql="select * from 数据表where 字段名=字段值order by 字段名[desc]"sql="select * from 数据表where 字段名like %字段值% order by 字段名[desc]"sql="select top 10 * from 数据表where 字段名order by 字段名[desc]"sql="select * from 数据表where 字段名in (值1,值2,值3)"sql="select * from 数据表where 字段名between 值1 and 值2"(2) 更新数据记录:sql="update 数据表set 字段名=字段值where 条件表达式"sql="update 数据表set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式"(3) 删除数据记录:sql="delete from 数据表where 条件表达式"sql="delete from 数据表" (将数据表所有记录删除)(4) 添加数据记录:sql="insert into 数据表(字段1,字段2,字段3 …) valuess (值1,值2,值3 …)"sql="insert into 目标数据表select * from 源数据表" (把源数据表的记录添加到目标数据表)(5) 数据记录统计函数:AVG(字段名) 得出一个表格栏平均值COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计MAX(字段名) 取得一个表格栏最大的值MIN(字段名) 取得一个表格栏最小的值SUM(字段名) 把数据栏的值相加引用以上函数的方法:sql="select sum(字段名) as 别名from 数据表where 条件表达式"set rs=conn.excute(sql)用rs("别名") 获取统的计值,其它函数运用同上。

超全SQL语句 ,含详细备注示例

超全SQL语句 ,含详细备注示例

从命令行连接到SQLPLUS:Sqlplus sys/密码as sysdbaAlter user scott account unlock;用户已更改。

conn scott/tiger已连接。

SQL单条语句:SQL>desc emp(表名); 描述这张表EMPNO:雇员编号COMM:津贴DNAME:部门名称LOC:部门所在地desc salgrade:描述薪水等级select语句:select * from emp:把这个表中的内容全部取出来select ename, sal * 12,from emp;取出雇员的年薪select 2 * 3 from emp;Desc dual;(dual 代表输出一个字段)select * from dual;select 2 * 3 from dual;只出一个结果select sysdate from dual;取出系统时间select ename, sal * 12 anunal_sal(或者”anunal sal”,加引号是保持原来的格式输出,它代表年薪名) from emp;select ename, comm from emp;输出每个人的津贴select ename, sal * 12 + comm from emp;年薪+津贴select ename || salfrom emp;|| 代表字符连接符select ename || ‘abc’ from emp;’’是把字符串内容加上select ename || ‘ abc‘‘def’ from emp;中间会打印出一个单引号Where是过滤语句:select * from emp where deptno = 10;取出部门编号为10的成员select * from emp where ename = ‘Clark’;=是等值判断select ename, sal from emp where sal > 1500;取出薪水大于1500的成员select ename, sal, deptno from where deptno < >10;取出部门编号不等于10 的部门成员和薪水select ename, sal from emp where ename > ‘cba’;字符串比较select ename,sal from emp where sal between 800 and 1500(where sal >= 800 and sl <= 1500);取出薪水在800到1500之间的成员select ename, sal, comm from emp where comm is null;取出津贴为空的成员select ename, sal, comm from emp where comm is not null;取出津贴不为空的成员select ename, sal, comm from emp where sal in <800, 1500, 2000>;取出薪水等于800,1500,2000的成员select ename, sal, comm from emp where ename in <’sMITH’, ‘KING’, ‘ABC’>;取出这三个人select ename, sa, hiredate from emp where hiredate > ‘20-2月-81’(‘20-2-1981’);取出入职时间为1981年2月20号的成员select ename, sal from emp where deptno = 10 and sal > 1000;select ename, sal from emp where deptno =10 or sal > 1000;注意两者结果不一样select ename from emp where ename like ‘%ALL%’;取出其中带有ALL字符串的成员名select ename from emp where ename like ‘_A%’;取出第二个字符是A的成员select ename from emp where ename like ‘%\%%’(‘%$%%’)(where ename like ‘%$%%’ escape ‘$’);告诉它这是转义字符数据排序:desc是降序、asc是升序(不写的话默认是升序)select * from dept order by deptno desc;按照deptno降序排列select empno, ename from emp order by empno asc;按照empno;升序排列//select empno , ename from emp where deptno < > 10 order by sal asc;select ename, sal * 12 annual_sal from emp where ename not like ‘_A%’ and sal > 800 order by sal desc;取出名字中第二个字母不是A且薪水大于800 的成员按降序排列sQL中的函数:select lower <ename> from emp;取出的名字都是小写select ename from emp where lower <ename> like ‘_a%’;先小写名字再取出第二个字母是a的成员select ename from emp where like ‘_a%’ or ename like ‘_A%’;select substr <ename, 2,3> from emp;从第二个开始截取三个名字select chr <65> from dual;把AsCII码转为字符select ascii <’A’> from dual;把A转为AsCII码select round <23.652> from dual;四舍五入输出为24(默认四舍五入到个位)select round <23.652, 2> from dual;保留两位小数,输出23.65select round <23.652, -1> from dual;四舍五入到十位,输出为20select to_char <sal, ‘$99,999.9999’> from emp;把sal转为固定格式,小数点后四位,小数点前五位(小数点后的必写,小数点前的位数不够可以省略)select to_char <sal, ‘L99,999.9999’> from emp;L为转为本地货币符select to_char <sal, ‘L00,000.0000’> from emp;注意:即使小数点前位数不够,也得把0补上select to_char <hiredate, ‘YYYY-MM-DD HH:MI:ss’> from emp;把入职时间改为固定格式select to_char <hiredate, ‘YYYY-MM-DD HH24:MI:ss’> from emp;HH为12进制,HH24为24进制select to_char <sysdate, ‘YYYY-MM-DD HH24:MI:ss’> from dual;select ename, hiredate from emp where hiredate > to_char <’1981-2-20 12:34:56’, ‘YYYY-MM-DD HH24:MI:ss’>;select sal from emp where sal > to_number <’$1,250.00’,’$9,999.00’>;取出薪水大于1250的select ename ,sal * 12 + nvl <comm,0> from emp;如果comm不存在则以0计算,nvl 就是为了避免空值select count <ename> from emp;select count <distinct deptno> from emp;Group by 分组语句:select avg <sal> from emp group by deptno;select deptno, avg <sal> from emp group by deptno;上述两项都是求部门的平均薪水select deptno,job max <sal> from emp group by deptno, job;select ename from emp where sal = < select max <sal>from emp>;取出薪水最高的那个人名select avg <sal>, deptno from emp group by deptno having avg<sal> > 2000;取出平均薪水大于2000的那些组(不能用where,因为它只控制单行输出,having是对分组进行限制)总结语句:select avg<sal> from emp where sal > 1200 group by deptno having avg<sal> > 1500 order by avg<sal> desc;子查询:Select ename, sal from emp where sal = <select max<sal> from emp>; select嵌套Select ename,sal from emp where sal > <select avg<sal> from emp>;//Select ename, sal, deptno from emp where sal in <select max<sal> from emp grup by emptno>;注意这句话有问题表连接:Select ename,sal from empjoin <select max <sal>, deptno from emp group by deptno> tOn <emp.sal = t.max_sal and emp.deptno = t.deptno>;Jion是连接的意思on里面是连接条件自连接:Select e1.ename, e2.ename from emp e1,emp e2 where e1.mgr = e2.empno;老版写法Select e1.ename,e2.ename from emp e1 join emp e2 on <e1.mgr = e2.empno>;新版写法Select e1.ename,e2.ename from emp e1 left join emp e2 on <e1.mgr =e2.empno>;左外连接:注意left的区别,把左边多余的拿出来等值连接:Select ename,dname from emp, dept where emp.deptno = dept.deptno;老版写法Select ensme,dname from emp join dept on <emp.deptno = dept.deptno>;新版写法Select ensme,dname from emp join dept using <deptno>; 和上面的写法一样,但不推荐使用using的用法非等值连接:Select ename, grade from emp e (e代表的是表的别名) join salgrade s on <e.sal between s.losal between and s.hisal>;三个表的连接写法:Select ename, dname, grade from emp e join dept d on <e.deptno = d.deptno> join salgrade s on <e.sal between s.losal and s.hisal> where ename not like ‘_A%’;求部门中哪些人的薪水最高:Select ename ,sal from emp join <select max<sal> max_sal, deptno from emp group by deptno> t on <emp.sal = t.max_sal and emp.deptno = t.deptno>;求部门平均薪水的等级:Select deptno, avg<sal>, grade from <select deptno, avg<sal> avg_sal from empgroup by deptno> t join salgrade s on <t.avg_sal between s.losal and s.hisal>;求出所有部门的每个人的薪水等级:Select deptno, ename,grade from emp join salgrade s on <emp.sal between s.losal and s.hisal>;求部门平均薪水的等级:Select deptno, avg<grade> from <Select deptno, ename,grade from emp join salgrade s on <emp.sal between s.losal and s.hisal>> t group by deptno;雇员中哪些人是经理人:Select ename from emp where empno in <select mgr from emp>;Select ename from emp where empno in <select distinct mgr from emp>;有效率的写法不准用组函数,求薪水的最高值(面试题):提示:用自连接select distinct sal from emp where sal not in <select distinct (distinct 是去掉重复的项) e1.sal from emp e1.job emp e2 on < e1.sal < e2.sal > >;求平均薪水最高的部门编号:Select deptno, avg_sal from<select avg<sal> avg_sal, deptno from emp group by deptno>where avg_sal =<select max<avg_sal> from<select avg<sal> avg_sal,deptno from emp group by deptno> >;另一种写法:Select deptno, avg_sal from<select avg<sal> avg_sal, deptno from emp group by deptno>where avg_sal =<select max<avg<sal>> from emp group by deptno >;求平均薪水最高的部门称号:Select dname from dept where deptno =<select deptno from<select avg<sal> avg_sal, deptno from emp group by deptno> where avg_sal =<select max<avg_sal> from<select avg<sal> avg_sal,deptno from emp group by deptno> >>;求平均薪水的等级最低的部门名称:Select dname, t1.deptno, grade, avg_sal from(Select deptno, grade, avg_sal from(Select deptno, avg<sal> avg_sal from emp group by deptno) tJoin salgrade s on (t.avg_sal between s.losal and s.hisal)) t1Join dept on (t1.deptno = dept.deptno)Where t1.grade =(Select min(grade) from(Select deptno, grade, avg_sal from(select deptno, avg(sal) avg_sal from emp group by deptno) t Join salgrade s on (t.avg_sal between s.losal and s.hisal)))求比普通员工最高薪水还要高的经理名称:select ename from empWhere empno in <select distinct mgr from emp where mgr is not null> and sal > select max<sal> from empwhere empno not in<select distinct mgr from emp where mgr is not null>求部门经理人中平均薪水最低的部门名称?求薪水最高的前5名雇员?//Select ename,sal from (select ename,sal from emp where empno in (select sal, //deptno from emp order by sal desc)) where rownum <= 5;求薪水最高的第六到第十名雇员?求最后入职的5名雇员?1、查找选了‘黎明’老师课的的姓名2、查有2门课以上不及格的学生姓名和平均成绩select sname,avgsalfrom (select sno,avg(scgrade) avgsalfrom (select s.sno,sname,cno,scgradefrom sc,swhere scgrade<60 and s.sno=sc.sno)group by snohaving count(*)>=2)table1, swhere s.sno=table1.sno3、查选了1和选了2的学生的姓名1、select snamefrom swhere sno not in(select snofrom c,scwhere o=oand c.cteacher='黎明')2、select sname,avgsalfrom (select sno,avg(scgrade) avgsalfrom (select s.sno,sname,cno,scgradefrom sc,swhere scgrade<60 and s.sno=sc.sno )group by snohaving count(*)>=2)table1, swhere s.sno=table1.sno3、select snamefrom s,scwhere s.sno=sc.snoand cno='1'intersectselect snamefrom s,scwhere s.sno=sc.snoand cno='2'1).求部门中哪些人的薪水最高select ename,emp.deptno,salfrom(select max(sal) maxsalary,deptnofrom empgroup by deptno)table1,empwhere emp.sal=table1.maxsalary2).求部门平均薪水的等级select deptno,gradefrom(select avg(sal) avgsal,deptnofrom empgroup by deptno)table1,salgradewhere avgsal between losal and hisal3).雇员中有哪些人是经理人select *from empwhere job='MANAGER'4).不准用组函数,求薪水的最高值(面试题)select salfrom empwhere sal>=all(select salfrom emp)5).求平均薪水最高的部门的部门的编号select deptno, avg(sal) maxsalfrom empgroup by deptnohaving avg(sal)>=all(select avg(sal) from emp group by deptno)6).求平均薪水最高的部门的部门名称select dnamefrom(select deptno, avg(sal) maxsalfrom empgroup by deptnohaving avg(sal)>=all(select avg(sal) from emp group by deptno))table1,deptwhere table1.deptno=dept.deptno7).求平均薪水等级最低的部门名称select dnamefrom deptwhere deptno=(select deptnofrom(select deptno,gradefrom(select avg(sal) avgsal,deptnofrom empgroup by deptno)table1,salgradewhere avgsal between losal and hisal)where grade<=all(select gradefrom(select deptno,gradefrom(select avg(sal) avgsal,deptnofrom empgroup by deptno)table1,salgradewhere avgsal between losal and hisal)) )8).求比普通员工的最高薪水还要高的经理人的名称select enamefrom empwhere job='MANAGER' and sal>=(select max(sal)from emp where job='CLERK')9).求薪水最高的前5名雇员select *from(select emp.*from emporder by sal desc)where rownum<=510.求薪水最高的第6到10名雇员(重点掌握)select *from(select table1.*,rownum rnfrom(select emp.*from emporder by sal desc)table1)where rn<=10 and rn>5比较效率:1、select * from emp where deptno = 10 and ename like ‘%A%’;(理论上效率高,如同短路语句)2、Select * from emp where ename like ‘%A%’ and deptno = 10;Create table stu(Id number(6),Name varchar2(20) constraint stu_name_nn not null,Sex number(1),Age number(3),Sdate date,Grade number(2) default 1,Class number(4),Email varchar2(50),Constraint stu_class_fk foreign key(class) references class(id),//定义外键Constraint stu_id_pk primary key(id),//定义主键Constraint stu_name_email_uni unique(email,name) //email和name必须相同)/Create table class(Id number(4) primary key,Name varchar2(20)not null)Alter table stu add(addr varchar2(100));(在表中加入一个字段)alter table stu modify(addr varchar2(50));(修改)Alter table stu drop(addr);(删除表中的字段)Insert into stu(id,name,email) values (1,’’a,’a’);Alter table stu add constraint stu_class_fk foreign key (class) references class(id);(加约束条件)Alter table stu drop constraint stu_class_fk;(删除约束条件)Select table_name from user_tables;Select conatraint_name from user_constraints;Select view_name from user_views;Select constraint_name,table_name from user_constraints;DML(数据操纵语言)语句:select、insert、delete、update(修改)Distinct:消除重复行Insert into dept values (50,’game’,’bj’);(已插入一行)Rollback;(回退已完成:回到没导入之前的状态)Create table emp2 as select * from emp;(备份一个表,内容和emp一模一样)Insert into dept2 values (50,’game’,’bj’);Insert into dept2(deptno,dname) values (60,’game2’);(增加指定的值)Insert into dept2 select * from dept;(把dept的值全部插入dept2中)Update emp2 set sal = sal*2,ename = ename || ‘-’ where deptno = 10;Select ename,sal from emp2 where deptno = 10;Update emp2 set sal = sal*2;Commit;(提交完成)此时,rollback已不起作用了,不会回到原始状态Delete from emp2;(所有都删掉)Delete from dept2 where deptno = 10;Rollback;DDL语句(数据定义语言):Create table t (a varchar2(10)); (创建表)Drop table t;(删除表)Alter user scott account unlock;(修改)DCL(数据控制语言)语句:Grant授权语句: grant [权限] on [要授予权限的数据库对象] to [使用者账户名称] with [授权选项]Revoke: deny [权限] on [要授予权限的数据库对象] to [使用者账户名称]常用的权限分配:grant授权:于为用户分配权限或角色GRANT CONNECT TO MARTIN;CONNECT角色允许用户连接至数据库,并创建数据库对象GRANT RESOURCE TO MARTIN;RESOURCE角色允许用户使用数据库中的存储空间GRANT CREATE SEQUENCE TO MARTIN;此系统权限允许用户在当前模式中创建序列,此权限包含在CONNECT角色中授予用户MARTIN 操作TEST表对象的权限允许用户查询TEST 表的记录:GRANT SELECT ON TEST TO MARTIN;允许用户更新TEST 表中的记录:GRANT UPDATE ON TEST TO MARTIN;允许用户插入、删除、更新和查询TEST 表中的记录:GRANT ALL ON TEST TO MARTIN;用新建用户来进行链接,发现权限不足。

SQL语句大全(很全)sql语句用法

SQL语句大全(很全)sql语句用法

SQL语句大全--语句功能--数据操作SELECT --从数据库表中检索数据行和列INSERT --向数据库表添加新数据行DELETE --从数据库表中删除数据行UPDATE --更新数据库表中的数据--数据定义CREATE TABLE --创建一个数据库表DROP TABLE --从数据库中删除表ALTER TABLE --修改数据库表结构CREATE VIEW --创建一个视图DROP VIEW --从数据库中删除视图CREATE INDEX --为数据库表创建一个索引DROP INDEX --从数据库中删除索引CREATE PROCEDURE --创建一个存储过程DROP PROCEDURE --从数据库中删除存储过程CREATE TRIGGER --创建一个触发器DROP TRIGGER --从数据库中删除触发器CREATE SCHEMA --向数据库添加一个新模式DROP SCHEMA --从数据库中删除一个模式CREATE DOMAIN --创建一个数据值域ALTER DOMAIN --改变域定义DROP DOMAIN --从数据库中删除一个域--数据控制GRANT --授予用户访问权限DENY --拒绝用户访问REVOKE --解除用户访问权限--事务控制COMMIT --结束当前事务ROLLBACK --中止当前事务SET TRANSACTION --定义当前事务数据访问特征--程序化SQLDECLARE --为查询设定游标EXPLAN --为查询描述数据访问计划OPEN --检索查询结果打开一个游标FETCH --检索一行查询结果CLOSE --关闭游标PREPARE --为动态执行准备SQL 语句EXECUTE --动态地执行SQL 语句DESCRIBE --描述准备好的查询---局部变量declare id char(10)--set id = '10010001'select id = '10010001'---全局变量---必须以开头--IF ELSEdeclare x int y int z intselect x = 1 y = 2 z=3if x > yprint 'x > y' --打印字符串'x > y'else if y > zprint 'y > z'else print 'z > y'--CASEuse panguupdate employeeset e_wage =casewhen job_level = ’1’ then e_wage*1.08 when job_level = ’2’ then e_wage*1.07 when job_level = ’3’ then e_wage*1.06else e_wage*1.05end--WHILE CONTINUE BREAKdeclare x int y int c intselect x = 1 y=1while x < 3beginprint x --打印变量x 的值while y < 3beginselect c = 100*x + yprint c --打印变量c 的值select y = y + 1endselect x = x + 1select y = 1end--WAITFOR--例等待1 小时2 分零3 秒后才执行SELECT 语句waitfor delay ’01:02:03’select * from employee--例等到晚上11 点零8 分后才执行SELECT 语句waitfor time ’23:08:00’select * from employee***SELECT***select *(列名) from table_name(表名) where column_name operator valueex:(宿主)select * from stock_information where stockid = str(nid)stockname = 'str_name'stockname like '% find this %'stockname like '[a-zA-Z]%' --------- ([]指定值的围)stockname like '[^F-M]%' --------- (^排除指定围)--------- 只能在使用like关键字的where子句中使用通配符)or stockpath = 'stock_path'or stocknumber < 1000and stockindex = 24not stock*** = 'man'stocknumber between 20 and 100stocknumber in(10,20,30)order by stockid desc(asc) --------- 排序,desc-降序,asc-升序order by 1,2 --------- by列号stockname = (select stockname from stock_information where stockid = 4)--------- 子查询--------- 除非能确保层select只返回一个行的值,--------- 否则应在外层where子句中用一个in限定符select distinct column_name form table_name --------- distinct指定检索独有的列值,不重复select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_name select stockname , "stocknumber" = count(*) from table_name group by stockname--------- group by 将表按行分组,指定列中有相同的值having count(*) = 2 --------- having选定指定的组select *from table1, table2where table1.id *= table2.id -------- 左外部连接,table1中有的而table2中没有得以null表示table1.id =* table2.id -------- 右外部连接select stockname from table1union [all] ----- union合并查询结果集,all-保留重复行select stockname from table2***insert***insert into table_name (Stock_name,Stock_number) value ("xxx","xxxx") value (select Stockname , Stocknumber from Stock_table2)---value为select语句***update***update table_name set Stockname = "xxx" [where Stockid = 3]Stockname = defaultStockname = nullStocknumber = Stockname + 4***delete***delete from table_name where Stockid = 3truncate table_name ----------- 删除表中所有行,仍保持表的完整性drop table table_name --------------- 完全删除表***alter table*** --- 修改数据库表结构alter table database.owner.table_name add column_name char(2) null .....sp_help table_name ---- 显示表已有特征create table table_name (name char(20), age smallint, lname varchar(30))insert into table_name select ......... ----- 实现删除列的方法(创建新表)alter table table_name drop constraint Stockname_default ---- 删除Stockname的default约束***function(/*常用函数*/)***----统计函数----AVG --求平均值COUNT --统计数目MAX --求最大值MIN --求最小值SUM --求和--AVGuse panguselect avg(e_wage) as dept_avgWagefrom employeegroup by dept_id--MAX--求工资最高的员工use panguselect e_namefrom employeewhere e_wage =(select max(e_wage)from employee)--STDEV()--STDEV()函数返回表达式中所有数据的标准差--STDEVP()--STDEVP()函数返回总体标准差--VAR()--VAR()函数返回表达式中所有值的统计变异数--VARP()--VARP()函数返回总体变异数----算术函数----/***三角函数***/SIN(float_expression) --返回以弧度表示的角的正弦COS(float_expression) --返回以弧度表示的角的余弦TAN(float_expression) --返回以弧度表示的角的正切COT(float_expression) --返回以弧度表示的角的余切/***反三角函数***/ASIN(float_expression) --返回正弦是FLOAT 值的以弧度表示的角ACOS(float_expression) --返回余弦是FLOAT 值的以弧度表示的角ATAN(float_expression) --返回正切是FLOAT 值的以弧度表示的角ATAN2(float_expression1,float_expression2)--返回正切是float_expression1 /float_expres-sion2的以弧度表示的角DEGREES(numeric_expression)--把弧度转换为角度返回与表达式相同的数据类型可为--INTEGER/MONEY/REAL/FLOAT 类型RADIANS(numeric_expression) --把角度转换为弧度返回与表达式相同的数据类型可为--INTEGER/MONEY/REAL/FLOAT 类型EXP(float_expression) --返回表达式的指数值LOG(float_expression) --返回表达式的自然对数值LOG10(float_expression)--返回表达式的以10 为底的对数值SQRT(float_expression) --返回表达式的平方根/***取近似值函数***/CEILING(numeric_expression) --返回>=表达式的最小整数返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型FLOOR(numeric_expression) --返回<=表达式的最小整数返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型ROUND(numeric_expression) --返回以integer_expression 为精度的四舍五入值返回的数据--类型与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型ABS(numeric_expression) --返回表达式的绝对值返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型SIGN(numeric_expression) --测试参数的正负号返回0 零值1 正数或-1 负数返回的数据类型--与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型PI() --返回值为π 即3.97936RAND([integer_expression]) --用任选的[integer_expression]做种子值得出0-1 间的随机浮点数----字符串函数----ASCII() --函数返回字符表达式最左端字符的ASCII 码值CHAR() --函数用于将ASCII 码转换为字符--如果没有输入0 ~ 255 之间的ASCII 码值CHAR 函数会返回一个NULL 值LOWER() --函数把字符串全部转换为小写UPPER() --函数把字符串全部转换为大写STR() --函数把数值型数据转换为字符型数据LTRIM() --函数把字符串头部的空格去掉RTRIM() --函数把字符串尾部的空格去掉LEFT(),RIGHT(),SUBSTRING() --函数返回部分字符串CHARINDEX(),PATINDEX() --函数返回字符串中某个指定的子串出现的开始位置SOUNDEX() --函数返回一个四位字符码--SOUNDEX函数可用来查找声音相似的字符串但SOUNDEX函数对数字和汉字均只返回0 值DIFFERENCE() --函数返回由SOUNDEX 函数返回的两个字符表达式的值的差异--0 两个SOUNDEX 函数返回值的第一个字符不同--1 两个SOUNDEX 函数返回值的第一个字符相同--2 两个SOUNDEX 函数返回值的第一二个字符相同--3 两个SOUNDEX 函数返回值的第一二三个字符相同--4 两个SOUNDEX 函数返回值完全相同QUOTENAME() --函数返回被特定字符括起来的字符串/*select quotename('abc', '{') quotename('abc')运行结果如下----------------------------------{{abc} [abc]*/REPLICATE() --函数返回一个重复character_expression 指定次数的字符串/*select replicate('abc', 3) replicate( 'abc', -2)运行结果如下----------- -----------abcabcabc NULL*/REVERSE() --函数将指定的字符串的字符排列顺序颠倒REPLACE() --函数返回被替换了指定子串的字符串/*select replace('abc123g', '123', 'def')运行结果如下----------- -----------abcdefg*/SPACE() --函数返回一个有指定长度的空白字符串STUFF() --函数用另一子串替换字符串指定位置长度的子串----数据类型转换函数----CAST() 函数语法如下CAST() (<expression> AS <data_ type>[ length ])CONVERT() 函数语法如下CONVERT() (<data_ type>[ length ], <expression> [, style])select cast(100+99 as char) convert(varchar(12), getdate())运行结果如下------------------------------ ------------199 Jan 15 2000----日期函数----DAY() --函数返回date_expression 中的日期值MONTH() --函数返回date_expression 中的月份值YEAR() --函数返回date_expression 中的年份值DATEADD(<datepart> ,<number> ,<date>)--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期DATEDIFF(<datepart> ,<number> ,<date>)--函数返回两个指定日期在datepart 方面的不同之处DATENAME(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分DATEPART(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分GETDATE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间----系统函数----APP_NAME() --函数返回当前执行的应用程序的名称COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值COL_LENGTH(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值COL_NAME(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名DATALENGTH() --函数返回数据表达式的数据的实际长度DB_ID(['database_name']) --函数返回数据库的编号DB_NAME(database_id) --函数返回数据库的名称HOST_ID() --函数返回服务器端计算机的名称HOST_NAME() --函数返回服务器端计算机的名称IDENTITY(<data_type>[, seed increment]) [AS column_name]) --IDENTITY() 函数只在SELECT INTO 语句中使用用于插入一个identity column列到新表中/*select identity(int, 1, 1) as column_nameinto newtablefrom oldtable*/ISDATE() --函数判断所给定的表达式是否为合理日期ISNULL(<check_expression>, <replacement_value>) --函数将表达式中的NULL 值用指定值替换ISNUMERIC() --函数判断所给定的表达式是否为合理的数值NEWID() --函数返回一个UNIQUEIDENTIFIER 类型的数值NULLIF(<expression1>, <expression2>)--NULLIF 函数在expression1 与expression2 相等时返回NULL 值若不相等时则返回expression1的值sql中的保留字action add aggregate allalter after and asasc avg avg_row_length auto_incrementbetween bigint bit binaryblob bool both bycascade case char characterchange check checksum columncolumns comment constraint createcross current_date current_time current_timestamp data database databases datedatetime day day_hour day_minute day_second dayofmonth dayofweek dayofyeardec decimal default delayeddelay_key_write delete desc describedistinct distinctrow double dropend else escape escapedenclosed enum explain existsfields file first floatfloat4 float8 flush foreignfrom for full functionglobal grant grants grouphaving heap high_priority hourhour_minute hour_second hosts identifiedignore in index infileinner insert insert_id intinteger interval int1 int2int3 int4 int8 intoif is isam joinkey keys kill last_insert_idleading left length likelines limit load locallock logs long longbloblongtext low_priority max max_rowsmatch mediumblob mediumtext mediumintmiddleint min_rows minute minute_secondmodify month monthname myisamnatural numeric no notnull on optimize optionoptionally or order outeroutfile pack_keys partial passwordprecision primary procedure processprocesslist privileges read realreferences reload regexp renamereplace restrict returns revokerlike row rows secondselect set show shutdownsmallint soname sql_big_tables sql_big_selectssql_low_priority_updates sql_log_off sql_log_update sql_select_limit sql_small_result sql_big_result sql_warnings straight_joinstarting status string tabletables temporary terminated textthen time timestamp tinyblobtinytext tinyint trailing totype use using uniqueunlock unsigned update usagevalues varchar variables varyingvarbinary with write whenwhere year year_month zerofill查看全文分类: ( 一般分类 ) :: 评论 (0) :: 静态网址 :: 引用 (0)常用SQL命令和ASP编程发表人:kendy517 | 发表时间: 2007年二月09日, 11:57在进行数据库操作时,无非就是添加、删除、修改,这得设计到一些常用的SQL语句,如下:SQL常用命令使用方法:(1) 数据记录筛选:sql="select * from 数据表 where 字段名=字段值 order by 字段名 [desc]"sql="select * from 数据表 where 字段名 like %字段值% order by 字段名 [desc]"sql="select top 10 * from 数据表 where 字段名 order by 字段名 [desc]"sql="select * from 数据表 where 字段名 in (值1,值2,值3)"sql="select * from 数据表 where 字段名 between 值1 and 值2"(2) 更新数据记录:sql="update 数据表 set 字段名=字段值 where 条件表达式"sql="update 数据表 set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式"(3) 删除数据记录:sql="delete from 数据表 where 条件表达式"sql="delete from 数据表" (将数据表所有记录删除)(4) 添加数据记录:sql="insert into 数据表 (字段1,字段2,字段3 …) valuess (值1,值2,值3 …)"sql="insert into 目标数据表 select * from 源数据表" (把源数据表的记录添加到目标数据表)(5) 数据记录统计函数:AVG(字段名) 得出一个表格栏平均值COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计MAX(字段名) 取得一个表格栏最大的值MIN(字段名) 取得一个表格栏最小的值SUM(字段名) 把数据栏的值相加引用以上函数的方法:sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"set rs=conn.excute(sql)用 rs("别名") 获取统的计值,其它函数运用同上。

(word完整版)数据库SQL经典语句(包含几乎所有的经典操作语言)

(word完整版)数据库SQL经典语句(包含几乎所有的经典操作语言)

1、说明:复制表(只复制结构,源表名:a 新表名:b)(Access可用)法一:select * into b from a where 1〈〉1法二:select top 0 * into b from a2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用)insert into b(a, b, c) select d,e,f from b;3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)insert into b(a, b, c) select d,e,f from b in ‘具体数据库' where 条件例子:。

.from b in ’”&Server.MapPath(”。

”)&”\data.mdb” &"’ where.。

4、说明:子查询(表名1:a 表名2:b)select a,b,c from a where a IN (select d from b )或者: select a,b,c from a where a IN (1,2,3)5、说明:显示文章、提交人和最后回复时间select a.title,a。

username,b。

adddate from table a,(select max(adddate) adddate from table where table。

title=a。

title) b6、说明:外连接查询(表名1:a 表名2:b)select a.a, a.b, a。

c, b。

c, b.d, b。

f from a LEFT OUT JOIN b ON a.a = b.c7、说明:在线视图查询(表名1:a )select * from (SELECT a,b,c FROM a) T where t.a 〉 1;8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括select * from table1 where time between time1 and time2select a,b,c, from table1 where a not between 数值1 and 数值29、说明:in 的使用方法select * from table1 where a [not] in (‘值1',’值2',’值4',’值6’)10、说明:两张关联表,删除主表中已经在副表中没有的信息delete from table1 where not exists ( select * from table2 where table1.field1=table2。

SQL查询语句大全集锦(经典)

SQL查询语句大全集锦(经典)

SQL查询语句大全集锦MYSQL查询语句大全集锦一、简单查询简单的Transact-SQL查询只包括选择列表、FROM子句和WHERE子句。

它们分别说明所查询列、查询的表或视图、以及搜索条件等。

例如,下面的语句查询testtable表中姓名为“张三”的nickname字段和email字段。

复制内容到剪贴板代码:SELECT `nickname`,`email`FROM `testtable`WHERE `name`='张三'(一) 选择列表选择列表(select_list)指出所查询列,它可以是一组列名列表、星号、表达式、变量(包括局部变量和全局变量)等构成。

1、选择所有列例如,下面语句显示testtable表中所有列的数据:复制内容到剪贴板代码:SELECT * FROM testtable2、选择部分列并指定它们的显示次序查询结果集合中数据的排列顺序与选择列表中所指定的列名排列顺序相同。

例如:复制内容到剪贴板代码:SELECT nickname,email FROM testtable3、更改列标题在选择列表中,可重新指定列标题。

定义格式为:列标题=列名列名列标题如果指定的列标题不是标准的标识符格式时,应使用引号定界符,例如,下列语句使用汉字显示列标题:复制内容到剪贴板代码:SELECT 昵称=nickname,电子邮件=email FROM testtable4、删除重复行SELECT语句中使用ALL或DISTINCT选项来显示表中符合条件的所有行或删除其中重复的数据行,默认为ALL。

使用DISTINCT选项时,对于所有重复的数据行在SELECT返回的结果集合中只保留一行。

5、限制返回的行数使用TOP n [PERCENT]选项限制返回的数据行数,TOP n说明返回n行,而TOP n PERCENT 时,说明n是表示一百分数,指定返回的行数等于总行数的百分之几。

例如:复制内容到剪贴板代码:SELECT TOP 2 * FROM `testtable`复制内容到剪贴板代码:SELECT TOP 20 PERCENT * FROM `testtable`(二) FROM子句FROM子句指定SELECT语句查询及与查询相关的表或视图。

数据库基本SQL语句大全

数据库基本SQL语句大全

数据库基本_SQL语句大全学会数据库是很实用D~~记录一些常用的sql语句...有入门有提高有见都没见过的...好全...收藏下...其实一般用的就是查询,插入,删除等语句而已....但学学存储过程是好事...以后数据方面的东西就不用在程序里搞喽..而且程序与数据库只要一个来回通讯就可以搞定所有数据的操作....一、基础1、说明:创建数据库Create DATABASE database-name2、说明:删除数据库drop database dbname3、说明:备份sql server--- 创建备份数据的deviceUSE masterEXEC sp_addumpdevice ‘disk‘, ‘testBack‘, ‘c:\mssql7backup\‘--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表create table tabnamecol1 type1 not null primary key,col2 type2 not null,..根据已有的表创建新表:A:create table tab_new like tab_old 使用旧表创建新表B:create table tab_new as select col1,col2… from tab_old definition only 5、说明:删除新表drop table tabname6、说明:增加一个列Alter table tabname add column col type注:列增加后将不能删除;DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度;7、说明:添加主键:Alter table tabname add primary keycol说明:删除主键:Alter table tabname drop primary keycol8、说明:创建索引:create unique index idxname on tabnamecol….删除索引:drop index idxname注:索引是不可更改的,想更改必须删除重新建;9、说明:创建视图:create view viewname as select statement删除视图:drop view viewname10、说明:几个简单的基本的sql语句选择:select from table1 where 范围插入:insert into table1field1,field2 valuesvalue1,value2删除:delete from table1 where 范围更新:update table1 set field1=value1 where 范围查找:select from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料排序:select from table1 order by field1,field2 desc总数:select count as totalcount from table1求和:select sumfield1 as sumvalue from table1平均:select avgfield1 as avgvalue from table1最大:select maxfield1 as maxvalue from table1最小:select minfield1 as minvalue from table111、说明:几个高级查询运算词A:UNION 运算符UNION 运算符通过组合其他两个结果表例如TABLE1 和TABLE2并消去表中任何重复行而派生出一个结果表;当ALL 随UNION 一起使用时即UNION ALL,不消除重复行;两种情况下,派生表的每一行不是来自TABLE1 就是来自TABLE2;B:EXCEPT 运算符EXCEPT 运算符通过包括所有在TABLE1 中但不在TABLE2 中的行并消除所有重复行而派生出一个结果表;当ALL 随EXCEPT 一起使用时EXCEPT ALL,不消除重复行;C:INTERSECT 运算符INTERSECT 运算符通过只包括TABLE1 和TABLE2 中都有的行并消除所有重复行而派生出一个结果表;当ALL 随INTERSECT 一起使用时INTERSECT ALL,不消除重复行;注:使用运算词的几个查询结果行必须是一致的;12、说明:使用外连接A、left outer join:左外连接左连接:结果集几包括连接表的匹配行,也包括左连接表的所有行;SQL: select , , , , , from a LEFT OUT JOIN b ON =B:right outer join:右外连接右连接:结果集既包括连接表的匹配连接行,也包括右连接表的所有行;C:full outer join:全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录;二、提升1、说明:复制表只复制结构,源表名:a 新表名:b Access可用法一:select into b from a where 1<>1法二:select top 0 into b from a2、说明:拷贝表拷贝数据,源表名:a 目标表名:b Access可用insert into ba, b, c select d,e,f from b;3、说明:跨数据库之间表的拷贝具体数据使用绝对路径Access可用insert into ba, b, c select d,e,f from b in ‘具体数据库’ where 条件例子:..from b in ‘"&"."&"\" &"‘ where..4、说明:子查询表名1:a 表名2:bselect a,b,c from a where a IN select d from b 或者: select a,b,c from a where a IN 1,2,35、说明:显示文章、提交人和最后回复时间select ,, from table a,select maxadddate adddate from table where = b6、说明:外连接查询表名1:a 表名2:bselect , , , , , from a LEFT OUT JOIN b ON =7、说明:在线视图查询表名1:aselect from Select a,b,c FROM a T where > 1;8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括select from table1 where time between time1 and time2select a,b,c, from table1 where a not between 数值1 and 数值29、说明:in 的使用方法select from table1 where a not in ‘值1’,’值2’,’值4’,’值6’10、说明:两张关联表,删除主表中已经在副表中没有的信息delete from table1 where not exists select from table2 where =11、说明:四表联查问题:select from a left inner join b on = right inner join c on = inner join d on = where .....12、说明:日程安排提前五分钟提醒SQL: select from 日程安排where datediff‘minute‘,f开始时间,getdate>513、说明:一条sql 语句搞定数据库分页select top 10 b. from select top 20 主键字段,排序字段from 表名order by 排序字段desc a,表名b where b.主键字段= a.主键字段order by a.排序字段14、说明:前10条记录select top 10 form table1 where 范围15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.select a,b,c from tablename ta where a=select maxa from tablename tb where =16、说明:包括所有在TableA 中但不在TableB和TableC 中的行并消除所有重复行而派生出一个结果表select a from tableA except select a from tableB except select a from tableC 17、说明:随机取出10条数据select top 10 from tablename order by newid18、说明:随机选择记录select newid19、说明:删除重复记录Delete from tablename where id not in select maxid from tablename group by col1,col2,...20、说明:列出数据库里所有的表名select name from sysobjects where type=‘U‘21、说明:列出表里的所有的sele ct name from syscolumns where id=object_id‘TableName‘22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case;select type,sumcase vender when ‘A‘ then pcs else 0 end,sumcase vender when ‘C‘ then pcs else 0 end,sumcase vender when ‘B‘ then pcs else 0 end FROM tablename group by type显示结果:type vender pcs电脑A 1电脑A 1光盘B 2光盘A 2手机B 3手机C 323、说明:初始化表table1TRUNCATE TABLE table124、说明:选择从10到15的记录select top 5 from select top 15 from table order by id asc table_别名order by id desc三、技巧1、1=1,1=2的使用,在SQL语句组合时用的较多“where 1=1” 是表示选择全部“where 1=2”全部不选,如:if strWhere =‘beginset strSQL = ‘select count as Total from ‘ + tblName + ‘ where ‘ + strWhere endelsebeginset strSQL = ‘select count as Total from ‘ + tblName + ‘‘end我们可以直接写成set strSQ L = ‘select count as Total from ‘ + tblName + ‘ where 1=1 安定‘+ strWhere2、收缩数据库--重建索引DBCC REINDEXDBCC INDEXDEFRAG--收缩数据和日志DBCC SHRINKDBDBCC SHRINKFILE3、压缩数据库dbcc shrinkdatabasedbname4、转移数据库给新用户以已存在用户权限exec sp_change_users_login ‘update_one‘,‘newname‘,‘oldname‘go5、检查备份集RESTORE VERIFYONLY from disk=‘E:\‘6、修复数据库Alter DATABASE dvbbs SET SINGLE_USERGODBCC CHECKDB‘dvbbs‘,repair_allow_data_loss WITH TABLOCKGOAlter DATABASE dvbbs SET MULTI_USERGO7、日志清除SET NOCOUNT ONDECLARE LogicalFileName sysname,MaxMinutes INT,NewSize INTUSE tablename -- 要操作的数据库名Select LogicalFileName = ‘tablename_log‘, -- 日志文件名MaxMinutes = 10, -- Limit on time allowed to wrap log.NewSize = 1 -- 你想设定的日志文件的大小M-- Setup / initializeDECLARE OriginalSize intSelect OriginalSize = sizeFROM sysfilesWhere name = LogicalFileNameSelect ‘Original Size of ‘ + db_name + ‘ LOG is ‘ + CONVERTVARCHAR30,OriginalSize + ‘ 8K pages or ‘ + CONVERTVARCHAR30,OriginalSize8/1024 + ‘MB‘FROM sysfilesWhere name = LogicalFileNameCreate TABLE DummyTransDummyColumn char 8000 not nullDECLARE Counter INT,StartTime DATETIME,TruncLog VARCHAR255Select StartTime = GETDATE,TruncLog = ‘BACKUP LOG ‘ + db_name + ‘ WITH TRUNCATE_ONLY‘DBCC SHRINKFILE LogicalFileName, NewSizeEXEC TruncLog-- Wrap the log if necessary.WHILE MaxMinutes > DATEDIFF mi, StartTime, GETDATE -- time has not expiredAND OriginalSize = Select size FROM sysfiles Where name = LogicalFileNameAND OriginalSize 8 /1024 > NewSizeBEGIN -- Outer loop.Select Counter = 0WHILE Counter < OriginalSize / 16 AND Counter < 50000 BEGIN -- updateInsert DummyTrans VALUES ‘Fill Log‘Delete DummyTransSelect Counter = Counter + 1ENDEXEC TruncLogENDSelect ‘Final Size of ‘ + db_name + ‘ LOG is ‘ + CONVERTVARCHAR30,size + ‘ 8K pages or ‘ + CONVERTVARCHAR30,size8/1024 + ‘MB‘FROM sysfilesWhere name = LogicalFileNameDrop TABLE DummyTransSET NOCOUNT OFF8、说明:更改某个表exec sp_changeobjectowner ‘tablename‘,‘dbo‘9、存储更改全部表Create PROCEDUREOldOwner as NVARCHAR128,NewOwner as NVARCHAR128ASDECLARE Name as NVARCHAR128DECLARE Owner as NVARCHAR128DECLARE OwnerName as NVARCHAR128 DECLARE curObject CURSOR FORselect ‘Name‘ = name,‘Owner‘ = user_nameuidfrom sysobjectswhere user_nameuid=OldOwnerorder by nameOPEN curObjectFETCH NEXT FROM curObject INTO Name, Owner WHILEFETCH_STATUS=0BEGINif Owner=OldOwnerbeginset OwnerName = OldOwner + ‘.‘ + rtrimNameexec sp_changeobjectowner OwnerName, NewOwnerend-- select name,NewOwner,OldOwnerFETCH NEXT FROM curObject INTO Name, Owner ENDclose curObjectdeallocate curObjectGO10、SQL SERVER中直接循环写入数据declare i intset i=1while i<30begininsert into test userid valuesiset i=i+1end。

sql常见语句用法

sql常见语句用法

SQL(Structured Query Language)是一种用于管理关系型数据库的编程语言。

以下是一些常见的SQL语句用法:1. SELECT 语句:用于从数据库表中获取数据。

```sqlSELECT 列名称 FROM 表名称;```例如:```sqlSELECT * FROM product;```这将返回 `product` 表中的所有列和行。

2. INSERT INTO 语句:用于向数据库表中插入数据。

```sqlINSERT INTO 表名 (列1, 列2, 列3) VALUES (值1, 值2, 值3);```例如:```sqlINSERT INTO product (name, price, pic_path) VALUES ('jack', 25, 'updown');```这将在 `product` 表中插入一条新的记录。

3. UPDATE 语句:用于更新数据库表中的数据。

```sqlUPDATE 表名 SET 列名1=值1, 列名2=值2 WHERE 条件;```例如:```sqlUPDATE product SET name="jack", price=35 WHERE id=2;```这将更新 `product` 表中 id 为 2 的记录的 `name` 和 `price` 列的值。

4. DELETE FROM 语句:用于从数据库表中删除数据。

```sqlDELETE FROM 表名 WHERE 条件;```例如:```sqlDELETE FROM product WHERE id=2;```这将删除 `product` 表中 id 为 2 的记录。

5. CREATE DATABASE 语句:用于创建新数据库。

```sqlCREATE DATABASE 数据库名称;```例如:```sqlCREATE DATABASE mydatabase;```这将创建一个名为 `mydatabase` 的新数据库。

sql常用语句大全

sql常用语句大全

sql常用语句大全以下是SQL中常用的语句:1. 查询语句:用于从数据库中检索数据。

- SELECT语句:用于从表中选择数据。

- FROM语句:用于从表中选择数据。

- WHERE语句:用于筛选数据。

- ORDER BY语句:用于排序数据。

- BY语句:用于对查询结果进行分组和排序。

2. 更新语句:用于更新数据库中的数据。

- UPDATE语句:用于在表中更新数据。

- WHERE语句:用于指定更新条件。

- SET语句:用于更新数据。

3. 删除语句:用于在数据库中删除数据。

- DELETE语句:用于从表中删除数据。

- WHERE语句:用于指定删除条件。

4. 创建语句:用于创建数据库、表、索引等。

-CREATE TABLE语句:用于创建一个表。

- AS语句:用于为表命名并提供别名。

- CONSTRAINT语句:用于为表创建约束条件。

5. 插入语句:用于向数据库中插入数据。

-INSERT INTO语句:用于向表中插入数据。

- VALUES语句:用于指定插入的数据。

6. 数据定义语句:用于定义数据库中的数据模型。

- PRIMARY KEY语句:用于为表创建主键。

- FOREIGN KEY语句:用于为表创建外键。

- KEY语句:用于为表创建索引。

7. 查询优化语句:用于优化查询性能。

- ANSI JOIN语句:用于连接两个表。

- NOT NULL语句:用于指定字段是否为非空。

- UNIQUE KEY语句:用于指定字段是否唯一。

8. 视图语句:用于简化复杂的查询。

- 视图定义语句:用于定义视图。

- 视图查询语句:用于查询视图中的数据。

9. 存储过程语句:用于执行复杂的操作并将结果存储回数据库中。

- 存储过程定义语句:用于定义存储过程。

- 存储过程执行语句:用于执行存储过程。

以上是SQL中常用的语句列表,SQL语句的使用可以极大地提高数据库的性能和灵活性。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
下列语句部分是Mssql语句,不可以在access中使用。
SQL分类:
DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE)
DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT)
DCL—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)
首先,简要介绍基础语句:
1、说明:创建数据库
CREATE DATABASE database-name
2、说明:删除数据库
drop database dbname
3、说明:备份sql server
--- 创建 备份数据的 device
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'
B: EXCEPT 运算符
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。
C: INTERSECT 运算符
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。
A:create table tab_new like tab_old (使用旧表创建新表)
B:create table tab_new as select col1,col2… from tab_old definition only
5、说明:
删除新表:drop table tabname
13、说明:一条sql 语句搞定数据库分页
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段
14、说明:前10条记录
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)
insert into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where..
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1
11、说明:几个高级查询运算词
B:right outer join:
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
C:full outer join:
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
其次,大家来看一些不错的sql语句
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!
6、说明:外连接查询(表名1:a 表名2:b)
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
7、说明:在线视图查询(表名1:a )
select * from (SELECT a,b,c FROM a) T where t.a > 1;
说明:
删除主键:Alter table tabname drop primary key(col)
8、说明:
创建索引:create [unique] index idxname on tabname(col….)
删除索引:drop index idxname
注:索引是不可更改的,想更改必须删除重新建。
11、说明:四表联查问题:
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....
12、说明:日程安排提前五分钟提醒
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5
A: UNION 运算符
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。
9、说明:
创建视图:create view viewname as select statement
删除视图:drop view viewname
10、说明:几个简单的基本的sql语句
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
9、说明:in 的使用方法
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)
10、说明:两张关联表,删除主表中已经在副表中没有的信息
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
select top 10 * form table1 where 范围
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
--- 开始 备份
BACKUP DATABASE pubs TO testBack
4、说明:创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
根据已有的表创建新表:
20、说明:列出数据库里所有的表名
select name from sysobjects where type='U'
21、说明:列出表里的所有的
select name from syscolumns where id=object_id('TableName')
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。
排序:select * from table1 order by field1,field2 [desc]
总数:select count * as totalcount from table1
求和:select sum(field1) as sumvalue from table1
法一:select * into b from a where 1<>1
法二:select top 0 * into b from a
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用)
insert into b(a, b, c) select d,e,f from b;
select top 10 * from tablename order by newid()
18、说明:随机选择记录
select newid()
19、说明:删除重复记录
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表
(select a from tableA ) except (select a from tableB) except (select a from tableC)
相关文档
最新文档