关于sql(20171218)
好记性不如烂笔头,给自己不中用的大脑写点东西,省的每次都要去扒。
查询
单表查询
SELECT column_name,column_name
FROM table_name;
FROM table_name;
#去重
SELECT DISTINCT column_name
FROM table_name;
tips:去重可以单列也可以多列,
#过滤
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
FROM table_name
WHERE column_name operator value;
tips:常用运算符
= | 等于 |
<>(!=) | 不等于 |
> | 大于 |
< | 小于 |
>= | 大于等于 |
<= | 小于等于 |
BETWEEN | 在某个范围 |
LIKE | 匹配某种模式 |
IN | 针对某列多个可能值 |
#and/or
逻辑与/逻辑或,真真得真/有真为真
#order by 排序
对查询结果进行排序,
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
tips:asc 升序 desc 降序
#limit 控制返回记录行数
SELECT column_name(s)
FROM table_name
LIMIT number;
FROM table_name
LIMIT number;
tips:limit n ,表示返回查询结果的前n条,limit n,m表示返回从n开始到m条记录
多表查询
join 用于结合多个表
#外连接(左连接、右连接、完全外连接)
左连接:以左表为主,即使右表没有匹配也会返回左表的所有记录
SELECT *
FROM TABLE1 t1
LEFT JOIN TABLE2 t2
ON t1.ID=t2.ID;
FROM TABLE1 t1
LEFT JOIN TABLE2 t2
ON t1.ID=t2.ID;
右连接:与左连接相反
SELECT *
FROM TABLE1 t1
RIGHT JOIN TABLE2 t2
ON t1.ID=t2.ID;
FROM TABLE1 t1
RIGHT JOIN TABLE2 t2
ON t1.ID=t2.ID;
完全外连接:mysql不支持,算了