精妙Sql语句 真经典

合集下载

经典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],..)5、说明:删除新表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查询语句是用来从数据库中检索数据的命令。

以下是一些常见的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语句大全(很全)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("别名") 获取统的计值,其它函数运用同上。

sql 段子

sql 段子

sql 段子在计算机程序设计领域,SQL(Structured Query Language,结构化查询语言)是一种用于管理关系数据库系统的语言。

尽管它看起来非常严肃和专业,但也有些有趣的“SQL段子”流传在开发者之间,让人们在编写和优化SQL查询时能够轻松一笑。

1. 一个SQL查询走进了一家酒吧,然后对酒保说:“你好,请给我一杯啤酒!”酒保回答:“对不起,我们这里只服务那些有名的人。

”SQL查询不以为然地说:“我就是那个‘ALL’表,有很多有名的字段都会来找我!”2. 一个开发者向另一个开发者抱怨说:“我每次编写SQL查询的时候,都觉得自己像是在让表发誓!”另一名开发者问:“为什么?”他回答道:“因为我总是用'FROM'开头、'WHERE'做限制,而最后却总是用'GROUP BY'!”3. 有一天,一只SQL查询和一只NoSQL查询走进了一家甜品店。

SQL查询点了个冰激凌,NoSQL查询则点了个水果沙拉。

当SQL查询看到NoSQL查询用叉子吃沙拉时,大吃一惊地说:“你吃得真快!”NoSQL查询回答:“我没有表。

”4. SQL查询对数据库管理员抱怨说:“我为什么总是和索引打交道?难道我是搜寻引擎吗?”数据库管理员耐心地回答:“不,你只是个索引大师。

”5. 一个开发者在写SQL查询时迷糊了,然后问同事:“我们数据库的数据明明一直都在那儿,为什么它们不出现在查询结果中?”同事回答:“你的查询太'WHERE'd(where’d)去了!”6. 一个开发者对另一个开发者说:“我的SQL查询速度慢得像蜗牛!”另一个开发者说:“那你就给你的查询添加一些'ESCARGOT'索引吧!”7. 一个SQL语句对另一个SQL语句说:“你看起来是个有条理的查询。

”另一个语句回答:“是的,我只是在按照'SELECT'顺序。

”8. 一名开发者在编写一条复杂的SQL查询时感到压力很大,他对自己说:“深呼吸,这只是个'JOIN'(接合)的过程!”只见他转身离开,决定去参加瑜伽课程以减压。

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语句5篇

高效SQL语句5篇

高效SQL语句5篇第一篇:高效SQL语句1.SELECT子句中避免使用“*”当你想在SELECT子句中列出所有的COLUMN时,使用动态SQL 列引用…*‟是一个方便的方法.不幸的是,这是一个非常低效的方法.实际上,ORACLE在解析的过程中, 会将“*” 依次转换成所有的列名, 这个工作是通过查询数据字典完成的, 这意味着将耗费更多的时间.2.使用DECODE函数来减少处理时间使用DECODE函数可以避免重复扫描相同记录或重复连接相同的表.例如:Sql代码1.SELECT COUNT(*),SUM(SAL)FROM EMP WHERE DEPT_NO = 0020 ANDENAME LIKE …SMITH%‟;2.SELECT COUNT(*),SUM(SAL)FROM EMP WHERE DEPT_NO = 0030 AND ENAME LIKE …SMITH%‟;SELECT COUNT(*),SUM(SAL)FROM EMP WHERE DEPT_NO = 0020 ANDENAME LIKE …SMITH%‟;SELECT COUNT(*),SUM(SAL)FROM EMP WHERE DEPT_NO = 0030 AND ENAME LIKE …SMITH%‟;你可以用DECODE函数高效地得到相同结果:Sql代码1.SELECT COUNT(DECODE(DEPT_NO,0020,‟X ‟,NULL))D0020_COUNT,2.COUNT(DECODE(DEPT_NO,0030,‟X ‟,NULL))D0030_COUNT,3.SUM(DECODE(DEPT_NO,0020,SAL,NUL L))D0020_SAL,4.SUM(DECODE(DEPT_NO,0030,SAL,NULL))D0030 _SAL5.FROM EMP WHERE ENAME LIKE …SMITH%‟;SELECT COUNT(DECODE(DEPT_NO,0020,‟X ‟,NULL))D0020_COUNT,COUNT(DECODE(DEPT_NO,0030,‟X ‟,NULL))D0030_COUNT,SUM(DECODE(DEPT_NO,0020,SAL,NULL))D0020_SAL,SUM(DECODE(DEPT_NO,0030,SAL,NULL))D0030_SA L FROM EMP WHERE ENAME LIKE …SMITH%‟;类似的,DECODE函数也可以运用于GROUP BY 和ORDER BY子句中.3.删除重复记录最高效的删除重复记录方法(因为使用了ROWID)Sql代码1.DELETE FROM EMP E WHERE E.ROWID >(SELECT MIN(X.ROWID)FROM EMP X WHERE X.EMP_NO = E.EMP_NO);DELETE FROM EMP E WHERE E.ROWID >(SELECT MIN(X.ROWID)FROM EMP X WHERE X.EMP_NO = E.EMP_NO);4.用TRUNCATE替代DELETE当删除表中的记录时,在通常情况下,回滚段(rollback segments)用来存放可以被恢复的信息,如果你没有COMMIT事务,ORACLE会将数据恢复到删除之前的状态(准确地说是恢复到执行删除命令之前的状况),而当运用TRUNCATE时, 回滚段不再存放任何可被恢复的信息.当命令运行后,数据不能被恢复.因此很少的资源被调用,执行时间也会很短.5.计算记录条数和一般的观点相反, count(*)比count(1)稍快,当然如果可以通过索引检索,对索引列的计数仍旧是最快的.例如 COUNT(EMPNO)6.用Where子句替换HAVING子句避免使用HAVING子句,HAVING 只会在检索出所有记录之后才对结果集进行过滤,这个处理需要排序、总计等操作,如果能通过WHERE子句限制记录的数目,那就能减少这方面的开销, 例如: Sql代码1.--低效2.SELECT REGION,AVG(LOG_SIZE)FROM LOCATION GROUP BY REGION HAVING REGION REGION!= …SYDNEY‟AND REGION!= …PERTH‟3.--高效4.SELECT REGION,AVG(LOG_SIZE)FROMLOCATION WHERE REGION REGION!= …SYDNEY‟ ND REGION!= …PERTH‟ GROUP BYREGION--低效SELECT REGION,AVG(LOG_SIZE)FROM LOCATION GROUP BY REGION HAVING REGION REGION!= …SYDNEY‟AND REGION!= …PERTH‟--高效SELECT REGION,AVG(LOG_SIZE)FROMLOCATION WHERE REGION REGION!= …SYDNEY‟ ND REGION!= …PERTH‟ GROUP BY REGION7.用EXISTS替代IN在许多基于基础表的查询中,为了满足一个条件,往往需要对另一个表进行联接.在这种情况下, 使用EXISTS(或NOT EXISTS)通常将提高查询的效率.Sql代码1.--低效2.SELECT * FROM EMP WHERE EMPNO > 0 AND DEPTNO IN(SELECT DEPTNO FROM DEPT WHERE LOC = …MELB‟)3.--高效:4.SELECT * FROM EMP WHERE EMPNO > 0 AND EXISTS(SELECT …X‟FROM DEPT WHERE DEPT.DEPTNO = EMP.DEPTNO AND LO C = …MELB‟)--低效SELECT * FROM EMP WHERE EMPNO > 0 AND DEPTNO IN(SELECT DEPTNO FROM DEPT WHERE LOC = …MELB‟) --高效:SELECT * FROM EMP WHERE EMPNO > 0 AND EXISTS(SELECT …X‟FROM DEPT WHERE DEPT.DEPTNO = EMP.DEPTNO AND LOC = …MELB‟)8.用NOT EXISTS替代NOT IN在子查询中,NOT IN子句将执行一个内部的排序和合并.无论在哪种情况下,NOT IN都是最低效的(因为它对子查询中的表执行了一个全表遍历).为了避免使用NOT IN,我们可以把它改写成外连接(Outer Joins)或NOT EXISTS.例如:SELECT …FROM EMPWHERE DEPT_NO NOT IN(SELECT DEPT_NO FROM DEPT WHERE DEPT_CAT=‟A‟);Sql代码1.--为了提高效率改写为:(方法一: 高效)SELECT ….FROM EMP A,DEPT B WHERE A.DEPT_NO = B.DEPT(+)AND B.DEPT_NO IS NULL AND B.DEPT_CAT(+)= …A‟2.--(方法二: 最高效)SELECT ….FROM EMP E WHERE NOT EXISTS(SELECT …X‟FROM DEPT D WHERE D.DEPT_NO = E.DEPT_NO AND DEPT_CAT = …A‟);3.--为了提高效率改写为:(方法一: 高效)SELECT ….FROM EMP A,DEPT B WHERE A.DEPT_NO =B.DEPT(+)AND B.DEPT_NO IS NULL AND B.DEPT_CAT(+)= …A‟4.--(方法二: 最高效)SELECT ….FROM EMP E WHERE NOT EXISTS(SELECT …X‟FROM DEPT D WHERE D.DEPT_NO = E.DEPT_NO AND DEPT_CAT = …A‟);9.用EXISTS替换DISTINCT当提交一个包含一对多表信息(比如部门表和雇员表)的查询时,避免在SELECT子句中使用DISTINCT.一般可以考虑用EXIST替换例如: Sql代码1.--低效:2.SELECT DISTINCT DEPT_NO,DEPT_NAMEFROM DEPT D,EMP E WHERE D.DEPT_NO = E.DEPT_NO3.--高效:4.SELECT DEPT_NO,DEPT_NAMEFROM DEPT D WHERE EXISTS(SELECT …X‟FROM EMP E WHERE E.DEPT_NO =D.DEPT_NO);5.--EXISTS 使查询更为迅速,因为RDBMS核心模块将在子查询的条件一旦满足后,立刻返回结果.--低效:SELECT DISTINCT DEPT_NO,DEPT_NAMEFROM DEPT D,EMP E WHERE D.DEPT_NO = E.DEPT_NO--高效:SELECT DEPT_NO,DEPT_NAMEFROM DEPT D WHERE EXISTS(SELECT …X‟FROM EMP E WHERE E.DEPT_NO = D.DEPT_NO);--EXISTS 使查询更为迅速,因为RDBMS核心模块将在子查询的条件一旦满足后,立刻返回结果.10.用索引提高效率索引是表的一个概念部分,用来提高检索数据的效率,实际上ORACLE使用了一个复杂的自平衡B-tree结构,通常通过索引查询数据比全表扫描要快,当ORACLE找出执行查询和Update语句的最佳路径时,ORACLE优化器将使用索引,同样在联结多个表时使用索引也可以提高效率,另一个使用索引的好处是,它提供了主键(primary key)的唯一性验证,除了那些LONG或LONG RAW数据类型, 你可以索引几乎所有的列.通常, 在大型表中使用索引特别有效.当然,你也会发现, 在扫描小表时,使用索引同样能提高效率,虽然使用索引能得到查询效率的提高,但是我们也必须注意到它的代价.索引需要空间来存储,也需要定期维护,每当有记录在表中增减或索引列被修改时,索引本身也会被修改,这意味着每条记录的INSERT , DELETE , UPDATE将为此多付出4 , 5 次的磁盘I/O,因为索引需要额外的存储空间和处理,那些不必要的索引反而会使查询反应时间变慢注:定期的重构索引是有必要的.11.避免在索引列上使用计算WHERE子句中,如果索引列是函数的一部分,优化器将不使用索引而使用全表扫描.举例:Sql代码1.--低效:2.SELECT …FROM DEPT WHERE SAL * 12 > 25000;3.--高效:4.SELECT … FROM DEPT WHERE SAL> 25000/12;--低效:SELECT …FROM DEPT WHERE SAL * 12 > 25000;--高效:SELECT … FROM DEPT WHERE SAL> 25000/12;12.用>=替代>Sql代码1.--如果DEPTNO上有一个索引2.--高效:SELECT *FROM EMPWHERE DEPTNO >=43.--低效:SELECT *FROM EMPWHERE DEPTNO >3--如果DEPTNO上有一个索引 4.--高效:SELECT *FROM EMPWHERE DEPTNO >=45.--低效:SELECT *FROM EMPWHERE DEPTNO >3两者的区别在于, 前者DBMS将直接跳到第一个DEPT等于4的记录而后者将首先定位到DEPTNO=3的记录并且向前扫描到第一个DEPT大于3的记录.第二篇:高效的SQL语句如何写高效率的SQL语句、Where子句中的连接顺序:ORACLE采用自下而上的顺序解析WHERE子句。

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中的if语句

sql中的if语句

sql中的if语句
嘿,朋友!你知道在 SQL 里,if 语句有多厉害吗?就好比你在黑暗中摸索,突然有了一盏明灯照亮前路!
比如说,你正在管理一个学生成绩的数据库。

你想根据成绩来给学
生分类,是优秀、良好还是需要努力。

这时候,if 语句就派上用场啦!
假设成绩大于等于 90 分,那就是优秀。

这就像是你在跑步比赛中
冲在最前面,遥遥领先,大家都为你欢呼!“IF score >= 90 THEN '优秀'”,是不是很清晰明了?
要是成绩在 80 到 89 分之间,那就是良好。

这好比你虽然没跑在最
前面,但也保持着不错的速度,稳定前进!“IF 80 <= score < 90 THEN '
良好'” 。

再比如,你要根据用户的购买金额来决定是否给他们发放优惠券。

如果购买金额超过 500 元,就发一张 50 元优惠券,这多棒啊!
SQL 中的 if 语句不就是这样嘛,根据不同的条件,做出不同的判断和处理,就像一个聪明的裁判,公正又准确。

你说,这么实用又强大的 if 语句,咱能不好好学学,好好用用吗?
我的观点是:SQL 中的 if 语句简直是数据库操作的神器,能让我们更灵活、更高效地处理数据,一定要熟练掌握!。

精妙SQL语句(二)

精妙SQL语句(二)

18、说明:随机选择记录
select newid()
19、说明:删除重复记录
Delete from tablename where id not in (select max(id) from tablename group by
col1,col2,...)
20、说明:列出数据库里所有的表名
set objRec = ObjConn.Execute(SQL)
Response.WriteRNumber & " = " & objRec("ID") & " " & objRec("c_email")
不必写出RNumber
和ID,你只需要检查匹配情况即可。只要你对以上代码的工作满意,你自可按需操作“随机”记录。Recordset没有包含其他内容,因此你很快就能找到你需要的记录这样就大大降低了处理时间。
SQL = "Select * FROM Customers Where ID = " & RNumber & " or ID = " & RNumber2 &
" or ID = " & RNumber3
假如你想选出10条记录(也许是每次页面装载时的10条链接的列表),你可以用BETWEEN
精妙SQL语句(二)- 精品下载 | 实用查询 | 词典查询 | 桌面壁纸 | 网址 | 笑话 | FLASH频道 | 天气文章资讯 | 站长工具 | 证件办理
| 闪字生成 | 广告代码 | 在线手册 | 有问必答经典文章
新闻资讯

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语句SET NOCOUNT ONSET ANSI_WARNINGS OFFSELECT OS.* INTO #Temp FROM(SELECT 0 AS FSumSort,u1.FItemID as FItemID,v1.FEmpID as FEmpID,v1.FDeptID as FDeptID,v1.FCustID as FSupplyID,ts.FNumber ASFSupplierNumber,ts.FName AS FSupplierName,v1.FBillNo,v1.FDate AS FDate,u1.FDate AS FDateDelivery,t.FNumber AS FNumber,t.FName AS FName,t.FModel,ta.FName AS FAuxPropName,tm.FName AS FUnitName,tc.FName AS FCurrencyName,u1.FAuxQty,u1.FAuxPriceDiscount,u1.FAllAmount,u1.FAllAmount * v1.FExchangeRate AS FAllAmountFor,ISNULL(u1.FAuxStockQty,0) AS FAuxStockQtyCommit,u1.FAuxQty-ISNULL(u1.FAuxStockQty,0) AS FAuxStockQtyUnCommit,ISNULL(u1.FAuxQtyInvoice,0) AS FAuxQtyInvoice,u1.FAuxQty-ISNULL(u1.FAuxQtyInvoice,0) AS FAuxQtyInvoiceUnCommit,ISNULL(tf.FAuxStockOutQty,0)/tm.FCoefficient asFAuxStockOutQtyCommit,(u1.FAuxQty-ISNULL(tf.FAuxStockOutQty,u1.FAuxQty)/tm.FCoefficient ) as FAuxStockOutQtyUnCommit,ISNULL(tmo.FAuxICMOQty,0)/tm.FCoefficient as FAuxICMOQty,(ISNULL(tmo.FAuxICMOStockQty,0)/tm.FCoefficient ) asFAuxICMOStockQty,(ISNULL(tmo.FAuxICMOQty,0)-ISNULL(tmo.FAuxICMOStockQty,0) )/tm.FCoefficient as FAuxICMOUnStockQty,ISNULL(tsub.FAuxSubContractQty,0)/tm.FCoefficient as FAuxSubContractQty,(ISNULL(tsub.FAuxSubContractStockQty,0)/ tm.FCoefficient )asFAuxSubContractStockQty,(ISNULL(tsub.FAuxSubContractQty,0)-ISNULL(tsub.FAuxSubContractStockQty,0))/tm.FCoefficient as FAuxSubContractUnStockQty,ISNULL(tr.FPOAuxQtyCommit,0)/tm.FCoefficient as FPOAuxQtyCommit,ISNULL(tr.FPOAuxStockQtyCommit,0)/tm.FC oefficient asFPOAuxStockQtyCommit,(ISNULL(tr.FPOAuxQtyCommit,0)-ISNULL(tr.FPOAuxStockQtyCommit,0))/tm.FCoefficient as FPOAuxStockQtyUnCommit,ISNULL(tp.FStdAllAmount,0)/v1.FExchangeRate AS FAmountInvoice,u1.FAllAmount-ISNULL(tp.FStdAllAmount,0)/v1.FExchangeRate AS FAmountInvoiceUnCommit,ISNULL(u1.FReceiveAmountFor_Commit,0) AS FReceiveAmountForCommit,u1.FAllAmount-ISNULL(u1.FReceiveAmountFor_Commit,0) AS FReceiveAmountForUnCommit,datediff(day,convert(varchar(100),v1.Fsettledate,23),getdate( )) Reminddate ,--(datediff(day,convert(varchar(100),Fsettledate,23),getdate()) asReminddate ,CASE WHEN v1.FStatus = 3 OR v1.FClosed = 1 THEN 'Y' ELSE '' END AS FClosed,CASE WHEN u1.FMrpClosed = 1 THEN 'Y' ELSE '' END AS FMrpClosed,t.FPriceDecimal,t.FQtyDecimalFROM SEOrder v1LEFT JOIN SEOrderEntry u1 ON v1.FInterID=u1.FInterIDLEFT JOIN t_Organization ts ON ts.FItemID in (v1.FCustID) and v1.Fsettledate is not nullLEFT JOIN t_AuxItem ta ON ta.FItemID=u1.FAuxPropIDLEFT JOIN t_MeasureUnit tm ON tm.FMeasureUnitID = u1.FUnitIDLEFT JOIN t_Currency tc ON tc.FCurrencyID=v1.FCurrencyID LEFT JOIN t_ICItem t ON t.FItemID=u1.FItemIDLEFT JOIN t_Emp te ON te.FItemID=v1.FEmpIDLEFT JOIN t_Department td ON td.FItemID=v1.FDeptIDLEFT JOIN (SELECT FOrderInterID,FOrderEntryID,SUM(FStdAllAmount) AS FStdAllAmount FROM (SELECT ui.FOrderInterID,ui.FOrderEntryID,SUM(ui.FStdAmount + CASE WHEN vi.FTranType IN(78,603,86) THEN 0 ELSE ui.FStdTaxAmount END) AS FStdAllAmountFROM ICSale viLEFT JOIN ICSaleEntry ui ON vi.FInterID=ui.FInterIDWHERE ISNULL(vi.FCancellation, 0) = 0 And ui.FOrderInterID > 0 And ui.FEntryID > 0 AND vi.FInterID NOT IN(SELECTDISTINCT FBillID FROM ICBillRelations_Purchase)GROUP BY ui.FOrderInterID,ui.FOrderEntryIDUNION ALLSELECT ti.FOrderInterID,ti.FOrderEntryID,SUM(tl.FQty*ui.FPrice*FExchangeRate + CASE WHEN vi.FTranType IN(78,603,86) THEN 0 ELSEtl.FQty*ui.FPrice*ui.FTaxRate*FExchangeRate/100 END) AS FStdAllAmountFROM ICSale viLEFT JOIN ICSaleEntry ui ON vi.FInterID=ui.FInterIDINNER JOIN ICBillRelations_Purchase tl ON vi.FInterID=tl.FBillIDINNER JOIN ICStockBillEntry ti ON ti.FInterID=tl.FMultiInterID AND ti.FEntryID=tl.FMultiEntryID WHERE ISNULL(vi.FCancellation, 0) = 0 And ui.FOrderInterID > 0 And ui.FEntryID > 0GROUP BY ti.FOrderInterID,ti.FOrderEntryID) t GROUP BY FOrderInterID,FOrderEntryID) tp ON u1.FInterID=tp.FOrderInterID AND u1.FEntryID=tp.FOrderEntryIDLEFT JOIN (SELECT FOrderInterID,FOrderEntryID,FAuxStockOutQty FROM (SELECT uf.FOrderInterID,uf.FOrderEntryID,SUM(FAuxQty-FAuxBackQty)*tuu.FCoefficient AS FAuxStockOutQtyFROM SEOutStock vfLEFT JOIN SEOutStockEntry uf ON vf.FInterID=uf.FInterIDLEFT JOIN t_MeasureUnit tuu on uf.FUnitID=tuu.FMeasureUnitIDWHERE ISNULL(vf.FCancellation, 0) = 0 And uf.FOrderInterID > 0 And uf.FEntryID > 0 AND vf.FTranType=83GROUP BY uf.FOrderInterID,uf.FOrderEntryID,tuu.FCoefficient) tf1) tf ON u1.FInterID=tf.FOrderInterID AND u1.FEntryID=tf.FOrderEntryIDLEFT JOIN (SELECT vm.FOrderInterID,vm.FItemID,sum(vm.FAuxQty)*tu.FCoefficient AS FAuxICMOQty,sum(vm.FAuxStockQty)*tu.FCoefficient AS FAuxICMOStockQty,vm.FSourceEntryIDFROM ICMO vmLEFT JOIN t_MeasureUnit tu on vm.FUnitID=tu.FMeasureUnitIDWHERE ISNULL(vm.FCancellation, 0) = 0 And vm.FOrderInterID > 0GROUP BY vm.FOrderInterID,tu.FCoefficient,vm.FItemID,vm.FSourceEntryID ) tmo ON u1.FInterID=tmo.FOrderInterID AND tmo.FItemID=u1.FItemID AND u1.FEntryID=tmo.FSourceEntryID LEFT JOIN (SELECT ts1.FInterIDOrder_SRC AS FOrderInterID,ts1.FEntryIDOrder_SRC ASFOrderEntryID,FAuxSubContractQty,FAuxSubContractStock Qty FROM (SELECT vs.FInterIDOrder_SRC,vs.FEntryIDOrder_SRC,SUM(vs.FAuxQty)*tu.FCoefficient AS FAuxSubContractQty,SUM(vs.FAuxStockQty)*tu.FCoefficient AS FAuxSubContractStockQtyFROM ICSubContractEntry vsLEFT JOIN ICSubContract us ON vs.FInterID=us.FInterIDLEFT JOIN t_MeasureUnit tu on vs.FUnitID=tu.FMeasureUnitIDWHERE ISNULL(us.FCancellation, 0) = 0 And vs.FInterID_SRC > 0GROUP BY vs.FInterIDOrder_SRC,vs.FEntryIDOrder_SRC,tu.FCoefficient ) ts1) tsub ON u1.FInterID=tsub.FOrderInterID AND u1.FEntryID=tsub.FOrderEntryIDLEFT JOIN (SELECT FOrderInterID,FOrderEntryID,SUM(FAuxQty) AS FPOAuxQtyCommit,SUM(FAuxStockQty) AS FPOAuxStockQtyCommit FROM(SELECT ur.FSourceInterId as FOrderInterID ,ur.FSourceEntryID as FOrderEntryID,SUM(ui.FAuxQty)*tu.FCoefficient AS FAuxQty,SUM(ui.FAuxStockQty)*tu.FCoefficient AS FAuxStockQty FROM POOrder viLEFT JOIN POOrderEntry ui ON vi.FInterID=ui.FInterIDLEFT JOIN PORequestEntry ur on ur.FInterID=ui.FSourceInterId AND ur.FItemID=ui.FItemID LEFT JOIN PORequest vr on vr.FInterID=ui.FSourceInterIdLEFT JOIN t_MeasureUnit tu on ui.FUnitID=tu.FMeasureUnitIDWHERE ISNULL(vi.FCancellation, 0) = 0 And ui.FSourceInterId > 0 And ui.FSourceEntryID > 0 AND vi.FInterID NOTIN(SELECT DISTINCT FBillID FROM ICBillRelations_S01T oP01)GROUP BY ur.FSourceInterId,ur.FSourceEntryID,tu.FCoefficientUNION ALLSELECT ti.FSourceInterId as FOrderInterID,ti.FSourceEntryID as FOrderEntryID,SUM(ui.FAuxQty)*tu.FCoefficient AS FAuxQty,SUM(ui.FAuxStockQty)*tu.FCoefficient AS FAuxStockQty FROM POOrder viLEFT JOIN POOrderEntry ui ON vi.FInterID=ui.FInterIDLEFT JOIN t_MeasureUnit tu on ui.FUnitID=tu.FMeasureUnitIDINNER JOIN ICBillRelations_S01ToP01 tl ON vi.FInterID=tl.FBillIDINNER JOIN PORequestEntry ti ON ti.FInterID=tl.FMultiInterID AND ti.FEntryID=tl.FMultiEntryID WHERE ISNULL(vi.FCancellation, 0) = 0 And ui.FSourceInterId > 0 And ui.FSourceEntryID > 0GROUP BY ti.FSourceInterId,ti.FSourceEntryID,tu.FCoefficient) t GROUP BY FOrderInterID,FOrderEntryID) trON u1.FInterID=tr.FOrderInterID AND u1.FEntryID=tr.FOrderEntryIDWHERE v1.FStatus>0 AND v1.FCancellation =0 AND v1.FClassTypeID<>1007101 AND v1.FDate>='2009-08-01' AND v1.FDate<='2015-08-28') OSIF EXISTS(SELECT TOP 1 FSumSort FROM #Temp WHERE FSumSort=0)BEGININSERT INTO#Temp(FSumSort,FSupplierNumber,FItemID,FEmpID,FDeptI D,FSupplyID,FBillNo,FClosed,FMrpClosed,FAuxQty,FAllAmount,F AllAmountFor,FAuxStockQtyCommit,FAuxStockQtyUnCommit,FA uxStockOutQtyCommit,FAuxStockOutQtyUnCommit,FAuxICMO Qty,FAuxICMOStockQty,FAuxICMOUnStockQty,FAuxSubContract Qty,FAuxSubContractStockQty,FAuxSubContractUnStockQty,FPO AuxQtyCommit,FPOAuxStockQtyCommit,FPOAuxStockQtyUnCo mmit,FAuxQtyInvoice,FAuxQtyInvoiceUnCommit,FAmountInvoice , FAmountInvoiceUnCommit, FReceiveAmountForCommit,FReceiveAmountForUnCommit,Rem inddate)SELECT101,'合计',0,0,0,0,'','','',SUM(ISNULL(FAuxQty,0)),SUM(ISNULL(FAllAmount, 0)),SUM(ISNULL(FAllAmountFor,0)),SUM(ISNULL(FAuxStockQtyC ommit,0)),SUM(ISNULL(FAuxStockQtyUnCommit,0)),SUM(ISNUL L(FAuxStockOutQtyCommit,0)),SUM(ISNULL(FAuxStockOutQtyU nCommit,0)),SUM(ISNULL(FAuxICMOQty,0)),SUM(ISNULL(FAuxIC MOStockQty,0)),SUM(ISNULL(FAuxICMOUnStockQty,0)),SUM(IS NULL(FAuxSubContractQty,0)),SUM(ISNULL(FAuxSubContractSto ckQty,0)),SUM(ISNULL(FAuxSubContractUnStockQty,0)),SUM(ISN ULL(FPOAuxQtyCommit,0)),SUM(ISNULL(FPOAuxStockQtyCom mit,0)),SUM(ISNULL(FPOAuxStockQtyUnCommit,0)), SUM(ISNULL(FAuxQtyInvoice,0)),SUM(ISNULL(FAuxQtyInvoi ceUnCommit,0)),SUM(ISNULL(FAmountInvoice,0)),SUM(ISNULL( FAmountInvoiceUnCommit,0)),SUM(ISNULL(FReceiveAmountFor Commit,0)),SUM(ISNULL(FReceiveAmountForUnCommit,0)),0 FROM #TempENDSELECT * FROM #T emp DROP TABLE #Temp874239493@/doc/3d15813998.html, jay19900304账套号查询SET NOCount onSelect a.*,d.FDBMSName,d.FVersion as FDBVersion From T_AD_KDACCOUNT_GL a,t_ad_dbtype d Where a.FDBType = d.FTypeID。

sql中insert into用法

sql中insert into用法

sql中insert into用法1. 嘿,你知道吗?sql 中的 insert into 那可是超有用的!就比如说,你想给一张表添加一些新数据,那就像给你的宝库放进新宝贝一样。

比如“insert into students (name, age) values ('小明', 20);”,这就把小明的信息加进去啦!2. 哇塞,sql 的 insert into 能做的事情可多啦!这不就像你在空白画布上描绘新的色彩吗?像这样“insert into products (name, price) values ('苹果', );”,新的商品信息就有了呀!3. 嘿呀,sql 里的 insert into 多神奇呀!它就如同给一个故事添加新的情节一样。

像“insert into orders (order_id, customer_name) values (1001, '张三');”,订单信息就丰富起来了呢!4. 哎呀,你可别小瞧了 sql 的 insert into 哟!这就好比给你的游戏角色添加新技能呢。

看这个例子“insert into employees (id, name) values (101, '李四');”,员工信息这不就来了嘛!5. 嘿,sql 的 insert into 可是个好东西呀!简直就像给你的花园种下新的花朵。

比如“insert into scores (student_id, score) values (201, 80);”,成绩就记录进去咯!6. 哇哦,sql 的 insert into 真的太厉害啦!不就像给你的美食大餐添加一道美味佳肴吗?“insert into categories (category_name) values ('电子产品');”,新的类别就有啦!7. 嘿哟,sql 中的 insert into 用处大着呢!就好像给你的旅行计划增加一个新的目的地。

plsql case语句

plsql case语句

plsql case语句
1. 嘿,你知道吗,PL/SQL 的 CASE 语句就像一个魔法开关!比如说,根据成绩来判断等级,成绩大于等于 90 就是“优秀”,这多神奇啊!
2. 哇塞,PL/SQL 的 CASE 语句简直太好用啦!就像走迷宫时有了明确的指引一样。

比如根据天气决定穿什么衣服,晴天就穿短袖,阴天就穿长袖。

3. 哎呀呀,PL/SQL 的 CASE 语句啊,那可是个厉害的角色!好比是一个智能的分配器。

例如根据顾客类型给予不同的优惠,会员就多给点折扣。

4. 嘿哟,PL/SQL 的 CASE 语句,这可是个宝贝呀!就如同根据不同口味选择不同的冰淇淋,喜欢甜的就选巧克力味。

5. 哇哦,PL/SQL 的 CASE 语句,它可真是神了!像根据不同的交通方式选择不同的路线一样。

比如坐公交就走这条道,打车就走那条道。

6. 哈哈,PL/SQL 的 CASE 语句,不就是像选电影类型一样嘛!爱情片就一种风格,动作片就另一种风格。

7. 哎哟喂,PL/SQL 的 CASE 语句,那可相当重要啊!就好像根据不同的节日装饰不同的房间,春节就红彤彤的。

8. 嘿嘿,PL/SQL 的 CASE 语句,这可真是个妙东西!如同根据不同
的兴趣爱好选择不同的活动,喜欢运动就去打球。

9. 呀,PL/SQL 的 CASE 语句,它的作用可大了去了!就跟根据不同的心情听不同的音乐一样,开心就听欢快的。

10. 哇,PL/SQL 的 CASE 语句,这绝对是个不可或缺的呀!好比根据不同的季节穿不同厚度的衣服,冬天就穿厚棉袄。

我觉得 PL/SQL 的 CASE 语句真的是超级实用,能让我们的编程工作变得轻松又有趣!。

sql高级语句

sql高级语句

sql高级语句
SQL高级语句可以包括以下内容:
1. JOIN语句:用于将多个表连接起来,可以使用不同的连接
方式(如INNER JOIN、LEFT JOIN、RIGHT JOIN等)来指
定连接条件。

2. 子查询:在查询中嵌套其他查询,可以用来解决复杂的查询需求。

3. 聚合函数:用于对数据进行统计和计算,包括SUM、AVG、COUNT、MAX、MIN等函数。

4. 窗口函数:与聚合函数类似,但可以在结果集的每一行上进行计算,可以对结果进行排序、分组和排名。

5. UNION和UNION ALL:用于合并多个查询的结果集,UNION会去除重复的行,而UNION ALL会保留重复的行。

6. 存储过程和触发器:用于存储和执行一系列的SQL语句,
可以在数据库中创建这些过程和触发器,并在需要时调用执行。

7. 索引:用于加快查询的速度,可以在表的列上创建索引,以便数据库引擎更快地搜索和定位数据。

8. 分区:将表按照特定的规则划分为多个子表,可以提高查询的效率和管理数据的灵活性。

9. 外键约束:用于保证数据的完整性,可以在表之间创建外键关系,来确保相关表中的数据始终保持一致。

10. CASE语句:用于根据条件执行不同的语句块,类似于编程语言中的if-else语句。

以上是一些常用的SQL高级语句,可以根据具体的需求选择合适的语句来完成数据库操作。

SQL语句大全 珍藏版2019

SQL语句大全 珍藏版2019

目录(01) SELECT .................................. ............... (2)查找SELECT "栏位名" FROM "表格名"(02) DISTINCT................................. ............... . (2)不同值SELECT DISTINCT "栏位名" FROM "表格名"(03) WHERE...................................... ............... (2)条件SELECT "栏位名" FROM "表格名" WHERE "条件"(04) AND OR ...................................... ............... . (3)条件并和或SELECT "栏位名" FROM "表格名" WHERE "简单条件" {[AND|OR] "简单条件"}(05) IN .............................................. ............... . (3)包含SELECT "栏位名" FROM "表格名" WHERE "栏位名" IN ('值一', '值二', ...)(06) BETWEEN.............................. ............... . (4)范围包含SELECT "栏位名" FROM " 表格名" WHERE "栏位名" BETWEEN '值一' AND '值二'(07) LIKE....................................... ............... (4)通配符包含SELECT "栏位名" FROM "表格名" WHERE "栏位名" LIKE {套式} -- 支持通配符‘_’单个字符'%' 任意字符(08) ORDER BY............................... ............... .. (5)排序SELECT "栏位名" FROM "表格名" [WHERE "条件"] ORDER BY "栏位名" [ASC, DESC] -- ASC 小到大DESC 大到小(09) 函数........................................ ............... .. (5)函数AVG (平均) COUNT (计数) MAX (最大值) MIN (最小值) SUM (总合) SELECT "函数名"("栏位名") FROM "表格名"(10) COUNT .................................... .............. .. (6)计数SELECT COUNT(store_name) FROM Store_Information WHERE store_name is not NULL -- 统计非空SELECT COUNT(DISTINCT store_name) FROM Store_Information -- 统计多少个不同(11) Group By .................................. .............. . (6)字段分组SELECT "栏位1", SUM("栏位2") FROM "表格名" GROUP BY "栏位1"(12) HAVING...................................... .............. (7)函数条件定位SELECT "栏位1", SUM("栏位2") FROM "表格名" GROUP BY "栏位1" HAVING (函数条件)(13) ALIAS........................................... .............. . (7)别名SELECT "表格别名"."栏位1" "栏位别名" FROM "表格名" "表格别名"(14) 连接................................................ . (8)SELECT A1.region_name REGION, SUM(A2.Sales) SALES FROM Geography A1, Store_Information A2 WHERE A1.store_name = A2.store_name GROUP BY A1.region_name(15) 外部连接........................................... .. (9)SELECT A1.store_name, SUM(A2.Sales) SALES FROM Georgraphy A1, Store_Information A2 WHERE A1.store_name = A2.store_name (+) GROUP BY A1.store_name(16) Subquery .............................. .............. .. (9)嵌套SELECT "栏位1" FROM "表格" WHERE "栏位2" [比较运算素] (SELECT "栏位1" FROM "表格" WHERE(17) UNION.................................... ............... .. (10)合并不重复结果[SQL 语句1] UNION [SQL 语句2](18) UNION ALL....................................... .............. . (11)合并所有结果[SQL 语句1] UNION ALL [SQL 语句2](19) INTERSECT..................................................... ............... . (11)查找相同值[SQL 语句1] INTERSECT [SQL 语句2](20) MINUS............................ ............... . (12)显示第一个语句中不在第二个语句中的项[SQL 语句1] MINUS [SQL 语句2] (21) Concatenate................................... ............... . (12)结果相加(串联)MySQL/Oracle:SELECT CONCAT(region_name,store_name) FROM Geography WHERE store_name = 'Boston';SQL Server:SELECT region_name + ' ' + store_name FROM Geography WHEREstore_name = 'Boston';(22) Substring ...................................................... ............... (13)取字符SUBSTR(str,pos) SUBSTR(str,pos,len)(23) TRIM ...... .............. (14)去空SELECT TRIM(' Sample '); TRIM()首尾, RTRIM()首, LTRIM()尾(24) Create Table ........... .............. .. (14)建立表格CREATE TABLE "表格名"("栏位1" "栏位1 资料种类","栏位2" "栏位2 资料种类",... )(25) Create View............................. .............. .. (15)建立表格视观表CREATE VIEW "VIEW_NAME" AS "SQL 语句"(26) Create Index........................................... ............... . (16)建立索引CREATE INDEX "INDEX_NAME" ON "TABLE_NAME" (COLUMN_NAME)(27) Alter Table.. .............. (16)修改表ALTER TABLE "table_name"[改变方式] -- ADD增加;DROP 删除;CHANGE 更名;MODIFY 更改类型(28) 主键.......................... (18)ALTER TABLE Customer ADD PRIMARY KEY (SID)(29) 外来主键....................................... ............ . (18)CREATE TABLE ORDERS(Order_ID integer,Order_Date date,Customer_SID integer,Amount double,Primary Key (Order_ID),Foreign Key (Customer_SID) references CUSTOMER(SID));(30) Drop Table................................................. ............... . (19)删除表DROP TABLE "表格名"(31) Truncate Table ................. ............... .. (20)清除表内容TRUNCATE TABLE "表格名"(32) Insert Into....................................... ............... .. (20)插入内容INSERT INTO "表格名" ("栏位1", "栏位2", ...) VALUES ("值1", "值2", ...)(33) Update ........................ ................ (20)修改内容UPDATE "表格名" SET "栏位1" = [新值] WHERE {条件}(34) Delete ......................................... .............. (21)DELETE FROM "表格名" WHERE {条件}SQL语句教程(01) SELECT是用来做什么的呢?一个最常用的方式是将资料从数据库中的表格内选出。

sql语录

sql语录

sql语录1. "数据库是计算机科学的灵魂。

" - Larry Ellison2. "数据就是一切。

" - Richard Campbell3. "我就是一个SQL驱动的机器。

" - Anonymous4. "SQL语言是计算机界的乐谱。

" - Chris Date5. "如果你不懂数据库,你就不懂计算机。

" - Roy Thomas Fielding6. "无论你使用什么编程语言,了解SQL都是必不可少的。

" - John Ousterhout7. "SQL是一个强大而精确的工具,可以让你从海量数据中提取有价值的信息。

" - Anonymous8. "通过SQL,你可以与数据库交流,就像与一个聪明的机器对话一样。

" - Anonymous9. "SQL是数据的魔术师,可以在你眨眼的间隙内完成惊人的计算。

" - Anonymous10. "SQL不仅仅是一种语言,还是一种思维方式。

" - Joe Celko11. "SQL就是一种艺术,可以将你的数据变成有用的信息。

" - Anonymous12. "SQL是获得信息宝藏的秘密钥匙。

" - Anonymous13. "无论你是管理数据还是分析数据,SQL都是你的得力助手。

" - Anonymous14. "SQL的美妙之处在于它的简洁与高效。

" - Anonymous15. "通过SQL,你可以轻松地完成复杂的数据操作,提高工作效率。

" - Anonymous。

sql主键语句

sql主键语句

sql主键语句SQL主键语句是数据库中非常重要的一部分,它可以保证数据的唯一性和完整性。

在数据库设计中,主键是一个非常重要的概念,它可以用来唯一标识一条记录。

在本文中,我们将列举出10个常用的SQL主键语句,以帮助读者更好地理解和应用主键。

1. 创建主键在创建表的时候,可以使用PRIMARY KEY关键字来定义主键。

例如:CREATE TABLE students (id INT PRIMARY KEY,name VARCHAR(50),age INT);在上面的例子中,我们定义了一个名为students的表,其中id列被定义为主键。

2. 修改主键如果需要修改主键,可以使用ALTER TABLE语句。

例如:ALTER TABLE studentsDROP PRIMARY KEY,ADD PRIMARY KEY (id, name);在上面的例子中,我们将原来的主键删除,并重新定义了一个由id 和name两列组成的主键。

3. 删除主键如果需要删除主键,可以使用ALTER TABLE语句。

例如:ALTER TABLE studentsDROP PRIMARY KEY;在上面的例子中,我们删除了名为students的表的主键。

4. 复合主键复合主键是由多个列组成的主键。

例如:CREATE TABLE orders (order_id INT,customer_id INT,order_date DATE,PRIMARY KEY (order_id, customer_id));在上面的例子中,我们定义了一个名为orders的表,其中order_id和customer_id两列组成了复合主键。

5. 自增主键自增主键是一种特殊的主键,它可以自动递增。

例如:CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(50),age INT);在上面的例子中,我们定义了一个名为students的表,其中id列被定义为自增主键。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
法一: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;
注:使用运算词的几个查询结果行必须是一致的。
12、说明:使用外连接
A、left outer join:
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。
SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type
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,ername,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) 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,...)
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表
(select a from tableA ) except (select a from tableB) except (select a from tableC)
17、说明:随机取出10条数据
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
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 )
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。
13、说明:一条sql 语句搞定数据库分页
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段
14、说明:前10条记录
SQL分类:
DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE)
DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT)
DCL—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)
首先,简要介绍基础语句:
1、说明:创建数据库
显示结果:
type vender pcs
电脑 A 1
电脑 A 1
光盘 B 2
光盘 A 2
手机 B 3
手机 C 3
23、说明:初始化表table1
TRUNCATE TABLE table1
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
6、说明:增加一个列
--- 开始 备份
BACKUP DATABASE pubs TO testBack
4、说明:创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
根据已有的表创建新表:
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
B:right outer join:
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
C:full outer join:
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
其次,大家来看一些不错的sql语句
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)
删除视图:drop view viewname
10、说明:几个简单的基本的sql语句
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
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)
Alter table tabname add column col type
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。
7、说明:添加主键: Alter table tabname add primary key(col)
说明:删除主键: Alter table tabname drop primary key(col)
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
绝对 精妙Sql语句 真经典,什得收藏
--------------------------------------------------------------------------------
本文关键字: 精妙Sql语句
下列语句部分是Mssql语句,不可以在access中使用。
CREATE DATABASE database-name
bname
3、说明:备份sql server
--- 创建 备份数据的 device
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'
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 )
相关文档
最新文档