SQL 基礎語句

  • SQL不區分大小寫
  • SQL需要分號

Create

用法一

CREATE TABLE [table] AS [select statement];

#樣例
CREATE TABLE cities AS
     SELECT 38 AS altitude, 122 AS longitude, “Berkeley” AS name UNION
     SELECT 42,                    71,                        "Cambridge"            UNION
     SELECT 45,                    93,                        "Minneapolis";

用法二

CREATE TABLE [table] [(create_definition,...)]

#用法樣例
CREATE TABLE numbers (n, note);
CREATE TABLE numbers (n UNIQUE, note);
CREATE TABLE numbers (n, note DEFAULT "No comment");

UNIQUE: 使得n是唯一的
DEFAULT: 設置默認值

Drop

DROP TABLE [table];        #刪除表

INSERT

INSERT INTO [table] VALUES [(value)];         #對一個表進行一整行的插入
#example
INSERT INTO numbers VALUES (4, "a"), (5, "b");


INSERT INTO [table(key)] VALUES [(value)];    #對一個表的某幾列進行插入,剩下默認爲null
#example
INSERT INTO numbers(n) VALUES (0), (1), (2), (3);


INSERT INTO [table] [select statement];       #用select來插入
#example
INSERT INTO numbers(n) SELECT n+8 from numbers;

UPDATE

UPDATE [table] SET [statement] WHERE [statement];   #通過where篩選需要更新的信息

#example
UPDATE numbers SET note = "aaa" WHERE n = 0;

DELETE

DELETE FROM [table] WHERE [statement];           #通過where篩選需要刪除的信息

#example
DELETE FROM numbers WHERE note = "No comment";

SELECT

SELECT [expression] AS [name], [expression] AS [name],;

SELECT [columns] FROM [table] WHERE [condition] ORDER BY [order] LIMIT [number];


#exapmle 1
SELECT a.parent, b.child 
FROM parents AS a, parents AS b
WHERE a.child = b.parent;

#example 2
CREATE TABLE grandparents AS
  SELECT a.parent AS grandog, b.child AS granpup
    FROM parents AS a, parents AS b
    WHERE b.parent = a.child;

ORDER BY

DESC      #降序
ASC       #升序(默認)

order by A,B             #這個時候都是默認按升序排列
order by A desc,B        #這個時候 A 降序,B 升序排列
order by A ,B desc       #這個時候 A 升序,B 降序排列

Aggregation

max()
min()
avg()
sum()
count()

GROUP BY

select [columns] from [table] group by [expression] having [expression];

Numerical Expressions

Combine values: +, -, *, /, %, and, or
Transform values: abs, round, not, -
Compare values: <, <=, >, >=, <>, !=, =

String Expressions

Combine: || 字符串拼接

sqlite> SELECT “hello,” || " world";
hello, world
substr(string, start_index, length) 獲取字串,start_index從1開始
instr(string, substring) 查找substring在string中的index

sqlite> CREATE TABLE phrase AS SELECT “hello, world” AS s;
sqlite> SELECT substr(s, 4, 2) || substr(s, instr(s, " ")+1, 1) FROM phrase;
low

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章