常用SQL语句

1.显示不重复的的值:

SELECT DISTINCT 列名 FROM 表名

2.显示前几条数据

SQLSERVER:SELECT TOP number|percent column_name|* FROM table_name

例:

SELECT TOP 5 * FROM table_name;

SELECT TOP 50 PERCENT column_name FROM table_name;

MYSQL: SELECT * FROM table_name LIMIT number

例:查询前十名的  SELECT * FROM table_name LIMIT 10;

ORACLE: SELECT * FROM table_name WHERE ROWNUM <=10

3.like+通配符

SELECT * FROM table_name where column_name LIKE pattern

%  替代一个或多个字符

_  替代一个字符

[charlist]  字符列中的任何单一字符

[^charlist]或者[!charlist]   不在字符列中的任何单一字符

4.IN

SELECT * FROM table_name WHERE column_name IN ('value1', 'value2');

5.BETWEEN

SELECT * FROM table_name WHERE column_name BETWEEN VALUE1 AND VALUE2

6.别名Alias

表别名:SELECT * FROM table_name AS alias_name WHERE alias_name = abc

列别名:SELECT column1_name AS alias_name1, column2_name AS alias_name2 FROM table_name;

7.JOIN

JOIN: 如果表中有至少一个匹配,则返回行

LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行

RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行

FULL JOIN: 只要其中一个表中存在匹配,就返回行

内连接JOIN = INTER JOIN 

SELECT column_name(s) FROM tableA INTER JOIN tableB ON tableA.column_name= tableB.column_name;

左连接 LEFT JOIN = LEFT OUTER JOIN

SELECT column_name(s) FROM tableA LEFT JOIN tableB ON tableA.column_name = tableB.column_name;

右连接 RIGHT JOIN = RIGHT OUTER JOIN

SELECT column_name(s) FROM tableA RIGHT JOIN tableA ON tableA.column_name = tableB.column_name;

FULL JOIN = FULL OUTER JOIN

SELECT column_name(s) FROM tableA FULL JOIN tableB ON tableA.column_name = tableB.column_name;

8.UNION和UNION ALL

UNION 操作符用于合并两个或多个 SELECT 语句的结果集。

请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。

默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。

SELECT column_names FROM tableA UNION SELECT column_names FROM tableB

SELECT column_names FROM tableA UNION ALL SELECT column_names FROM tableB

9.SELECT INTO

SELECT INTO 语句从一个表中选取数据,然后把数据插入另一个表中。

SELECT INTO 语句常用于创建表的备份复件或者用于对记录进行存档。

SELECT * INTO new_table IN [externaldatabase] FROM old_table;

SELECT column_name(s) INTO new_table IN [externaldatabase] FROM old_table;

10.CREATE DATABASE

CREATE DATABASE database_name;

11.CREATE TABLE

CREATE TABLE table_name

{

列名称1,数据类型;

列名称n,数据类型;

}

12.查看端口号:show global variables like 'port';

13.新建数据库设置编码为utf8:CREATE DATABASE databasename CHARACTER SET utf8;

你可能感兴趣的:(常用SQL语句)