首页 > 数据库 >【数据库原理、编程与性能】Basic SQL Query Language

【数据库原理、编程与性能】Basic SQL Query Language

时间:2023-06-20 11:37:41浏览次数:44  
标签:Language cid Basic agents SQL aid where select



文章目录

  • 1. History of SQL
  • 2. Capabilities of SQL
  • 2.1 综合统一
  • 2.2 高度非过程化
  • 2.3 面向集合的操作方式
  • 2.4 SQL以同一种语法结构提供两种使用方式
  • 2.5 语言简捷,易学易用
  • 3. SQL语句
  • 3.1 Create语句
  • 3.2 Select语句
  • 3.3 Subquery语句
  • 3.3.1 定义
  • 3.3.2 Conception(概念)
  • 3.3.3 predicate(谓词)
  • 3.3.4 set function
  • 3.4 Insert语句
  • 3.5 Update语句
  • 3.6 Delete语句


1. History of SQL

SQL —— Structured Query Language

  • 1986年,ANSI (American National Standard Institute) 的数据库委员会批准SQL作为”关系数据库语言的美国标准”;
  • 1989年,ANSI与ISO(International Standard Origination)联合修改完善后,颁布了SQL_89国际标准;
  • 1992 年,公布SQL_92 标准;
  • 1999 年,公布SQL_99,增加对Object-Relation Model;

2. Capabilities of SQL

介于“关系代数、关系演算”之间的结构化查询语言

2.1 综合统一

  • 集DDL 、DML 、DCL 于一体,可独立完成DB 生命周期中的全部活动;
  • DB运行后,可根据需要随时修改模式,不影响DB的运行,系统具有良好的可扩展性;

2.2 高度非过程化

SQL操纵数据只需提出“做什么”,无须指明“怎样做”,数据存取路径、操作过程均由DBMS自动完成。

2.3 面向集合的操作方式

关系模型下,SQL数据操作one time a set;

2.4 SQL以同一种语法结构提供两种使用方式

  • 是自含式语言(可独立联机交互使用),又是嵌入式语言(嵌入到其它高级语言中);
  • 两种使用方式下,SQL的语法结构基本一致;

2.5 语言简捷,易学易用

  • 数据查询 select
  • 数据操纵 insert, update, delete
  • 数据控制 grant, revoke

3. SQL语句

3.1 Create语句

CREATE TABLE tablename (colname datatype [ not null ]{ , colname datatype [ not null ] … }[ , PRIMARY KEY ( colname { , colname … } ) ])

eg 1:

create table customers(cid char(40) not null, cname varchar(13), city varchar(20), discnt real, primary key(cid));

eg 2:

create table orders (ordno integer not null, month char(3),
cid char(4), aid char(3), pid char(3), qty integer, dollars double precision,
primary key (ordno),
foreign key(aid) reference agents(aid),
foreign key(cid) reference customers(cid),
foreign key(pid) reference products(pid) );

3.2 Select语句

Select [ all ∣ distinct ] < 目标列表达式 > [< 目标列表达式>]
From < 表名或视图名>[ ,< 表名或视图名>]
Where < 条件表达式>
Group by <列名1> [ Having< 条件表达式>]
Order by <列名2> [ ASC ∣DESC ] ;

eg:

select c.cname, c.cid, a.aname, a.aid, sum(o.dollars) as casales
from customers c, orders o, agents a
where c.cid = o.cid and o.aid = a.aid
group by c.cname, c.cid, a.aname, a.aid
having sum(o.dollars) >= 900.00
order by 5 desc;

3.3 Subquery语句

3.3.1 定义

A Select statement appearing within another Select statement.

eg: Find aids in Duluth or Dallas, and make a subquery to select aid from agents.

select distinct cid from orders
where aid in (select aid from agents
where city = ' Duluth ' or city = 'Dallas');

3.3.2 Conception(概念)

  • Uncorrelated Subquery(不相关子查询)
  • Can pre-calculate the inner SQL statement
    (the inner Subquery is completely independent of the outer one)
  • Correlated Subquery(相关子查询)
  • Can’t pre-calculate the inner loop, because the Subquery using data from an outer Select.

3.3.3 predicate(谓词)

  • in

expr [NOT] in (Subquery) | expr [NOT] in (val1{ , val2…})

  • Comparison Predicates (some、any、all)

=some <>some <=some >some <some >=some
=any <>any <=any >any <any >=any
=all <>all <=all >all <all >=all

eg: Find all customers who have the same discount as that of any of the customers in Dallas or Boston.

select cid, cname from customers c where discnt=some(select discnt from c where city in ('Dallas', 'Boston'));

  • EXISTS Predicate(EXIST)

[NOT] EXIST (Subquery)
EXIST(subquery) is true <==> subquery is a non-empty set
NOT EXIST(subquery) is true <==> subquery is an empty set

  • The UNION Operator

Subquery UNION [ALL] Subquery.(不含all则取并集,含all则不去除重复元组)

eg: We wish to list of cities where either a customer or an agent, or both, is based.

  • SQL1: select city from customers union select city from agents; /* no duplicate rows */
  • SQL2: select city from customers union all select city from agents; /* has duplicate rows */
  • Division

双重否定表肯定。(具体请看实例)

eg 1 :Find cids of customers who place orders with ALL agents based in New York.

  • SQL中无全称量词,需做等价转换,题目变为“找cids,他没有一张订单不是从New York 的agents处代理的”。

select cid from customers c where not exists (select * from agents a where city = 'New York' and not exists (select * from orders x where x.aid = a.aid and x.cid = c.cid) );

eg 2 :Get the aids of agents in New York or Duluth who place orders for all products costing more than a dollar.

  • 找New York/Duluth 的aids,没有一件1 美元以上的产品不是他们代理的。

select aid from agent a where (a.city=„New York‟ or a.city=„Duluth‟) and not exists (select p.pid from product p where p.price>1.0 and not exists (select * from orders x where x.pid = p.pid and x.aid = a.aid ) );

  • LIKE

WHERE column [NOT] LIKE pattern

LIKE通常与通配符%一起使用,%表示通配pattern中出现的内容,而不加通配符%的LIKE语法,表示精确匹配,其实际效果等同于 = 等于运算符

eg:

SELECT * FROM user WHERE username LIKE '小%';--找到名字以小字开头的元组

3.3.4 set function

Five types : count(), max(), min(), sum(), avg();

3.4 Insert语句

INSERT INTO tablename [(column {, column…})]
{VALUES (expr | null { , expr | null…}) | subquery}

eg 1 :Add a row specified values to the orders table. (no qty or dollars, so on this new row they are null)

insert into orders (ordno, month, cid, aid, pid) values('1107', 'aug', 'c006', 'a04', 'p01');

eg 2 :Create a new table Swcusts of Southwestern customers, and insert into all customers from Dallas and Austin.

insert into swcusts select * from customers where city in ('Dallas', 'Austin');

3.5 Update语句

UPDATE tablename
SET colname = {expr | null | (subquery)}
{, {column = expr |null | (subquery)…}}
[where search_condition];

eg 1 :Give All agents in New York a 10% raise in the percent commission they earn on an order.

UPDATE agents SET percent = 1.1*percent WHERE city = 'New York';

3.6 Delete语句

DELETE FROM tablename [WHERE search_condition];

eg 1 :Delete all agents in New York.

delete from agents where city = 'New York';

eg 2 :Delete agents who have total orders of less than $600.

delete from agents where aid in ( select aid from orders group by aid having sum(dollars) < 600 );


标签:Language,cid,Basic,agents,SQL,aid,where,select
From: https://blog.51cto.com/u_16165815/6521620

相关文章

  • [ERROR] Aborting 安装mysql5.7报错
    2023-06-20T03:17:11.632401Z0[ERROR]Fatalerror:Can'topenandlockprivilegetables:Table'mysql.user'doesn'texist2023-06-20T03:17:11.632414Z0[ERROR]Fatalerror:FailedtoinitializeACL/grant/timezonesstructuresorfailed......
  • MySQL单表查询练习(条件_模糊_分组_聚合_排序)
    练习所用数据表•部门表CREATETABLEDEPT(DEPTNOINTPRIMARYKEY,–部门编号DNAMEVARCHAR(14),–部门名称LOCVARCHAR(13)–部门地址);INSERTINTODEPTVALUES(10,‘ACCOUNTING’,‘NEWYORK’);INSERTINTODEPTVALUES(20,‘RESEARCH’,‘DALLAS’);......
  • 解决PostgreSQL分组聚合时SELECT中字段必须在group或聚合函数中的问题(转自知乎仅供自
    PG的分组函数是比较严格的。你的select字段必须得存在于group子句、或者聚合函数中才行。假设场景是这样的:表结构name、class、score我现在要按照name分组,聚合score数据,还能查出额外的这个class字段如果是MySQL,你可以直接groupname然后selectclass,avg(score),但是你在P......
  • Mysql - 统计数据
    QA统计数据是做什么的?为了解释器在计算代价时,选择最优的方案.这个值如果与实际值差距过大,会导致执行顺序的变更.统计数据有哪些?对表的统计数据-mysql.innodb_table_stats对表索引的统计数据-mysql.innodb_index_stats统计数据存在哪?有两种方式,一种存在磁盘,一种存在......
  • PromSQL v2.29
    启动参数负偏移量:启动时增加--enable-feature=promql-negative-offset时间修饰符:@启动时增加--enable-feature=promql-at-modifier数据类型分类即时向量:Instant-vector范围向量:Range-vector标量:Scalar字符串(未启用)查询指标名//结果为即时向量,所有该指标的结果,......
  • MySql InnoDB 存储引擎表优化
    一、InnoDB表存储优化1、OPTIMIZETABLE适时的使用OPTIMIZETABLE语句来重组表,压缩浪费的表空间。这是在其它优化技术不可用的情况下最直接的方法。OPTIMIZETABLE语句通过拷贝表数据并重建表索引,使得索引数据更加紧凑,减少空间碎片。语句的执行效果会因表的不同而不同。过大......
  • 什么是MySQL
    什么是MySQLMySQL是一个关系型数据库,它采用表的形式来存储数据。你可以理解成是Excel表格,既然是表的形式存储数据,就有表结构(行和列)。行代表每一行数据,列代表该行中的每个值。列上的值是有数据类型的,比如:整数、字符串、日期等等。数据库的三大范式第一范式1NF确保数据库表字段......
  • 宝塔面板中使用Mysql命令快速导入大容量数据库
    在宝塔面板中,文件栏目中打开/www/backup/database文件夹,把我们的数据库上传到此文件夹中。(一般导入的数据库都会上传到这个文件夹,方便以后管理)点击旁边的终端,打开宝塔终端界面。输入账号及密码进入终端管理。(如果忘记密码,在软件商店里面找到Linux工具箱1.4里面可以设置......
  • postgresql json取值为何这么慢?
    一、缘起慢sql分析,总行数80w+,通过监控分析慢SQL,某个查询耗时超1s。比较特殊的是:其中有个字段info是jsonb类型,写法:info::json->'length'aslength同样的查询条件查这个字段和不查这个字段相差3.3倍那看来就是json取值拖垮了查询的性能。取jsonb中的字段有多种取法(如下),那......
  • sql server 查看备份记录
    SELECTCONVERT(CHAR(100),SERVERPROPERTY('Servername'))ASServer,msdb.dbo.backupset.database_name,msdb.dbo.backupset.backup_start_date,msdb.dbo.backupset.backup_finish_date,msdb.dbo.backupset.expiration_date,CASEm......