MySQL:SQL的语法和规则

SELECT col, col, col; //找什么
FROM table; //从哪找
WHERE col条件 ; //条件是啥

条件:数字(where)

当查找条件col是数字:
select * from table where col = 1;

OperatorSQL Example解释
, !=, < <=, >, >=col !=4等于 大于 小于
BETWEEN … AND …col BETWEEN 1 AND 10在X和X之间
NOT BETWEEN … ANDNOT BETWEEN 1 AND 10不在X和X之间
IN (…)col IN (2, 4, 6)在X集合中
NOT IN (…)col NOT IN (1, 3, 5)不在集合X中
条件:文本(where)

当查找的条件col是文本
select * from table where col like ‘%jin’;

OperatorSQL Example解释
=col =“abc”等于
!= or <>col <> “abc”不等于
LIKEcol LIKE “ABC”等于
NOT LIKEcol NOT LIKE “ABC”不等于
%col LIKE “%AT%” (matches “AT”, “ATTIC”, “CAT” or even “BATS”)模糊匹配
_col LIKE “AN_” (matches “AND”, but not “AN”)模糊匹配(单字符)
IN (…)col IN (“A”, “B”, “C”)在集合中
NOT IN (…)col NOT IN (“D”, “E”, “F”)不在集合中
排序(rows)

需要对结果rows排序和筛选部分rows:
select * from table where col > 1 order by col asc limit 2 offset 2

OperatorSQL Example解释
ORDER BYORDER BY col ASC/DESC按col排序
ASCORDER BY col ASC升序
DESCORDER BY col DESC降序
LIMIT OFFSETLIMIT num_limit OFFSET num_offset从offset取limit
ORDER BYORDER BY col1 ASC,col2 DESC多列排序
连表(join)

当查找的数据在多张关联table里:
select * from table1 left join table2 on table1.id = table2.id where col > 1

OperatorSQL Example解释
JOIN … ON …t1 JOIN t2 ON t1.id = t2.id按ID连成1个表
INNER JOINt1 INNER JOIN t2 ON t1.id = t2.id只保留id相等的row
LEFT JOINt1 LEFT JOIN t2 ON t1.id = t2.id保留t1的所有row
RIGHT JOINt1 RIGHT JOIN t2 ON t1.id = t2.id保留t2的所有row
IS/IS NOT NULLcol IS/IS NOT NULLcol是不是为null
算式(select / where)

当需要对select的col 或 where条件的col 经过一定计算后才能使用:
select ,col2 from table where col/2 > 1

OperatorSQL Example解释
+ - * / %col1 + col2col加减乘除
substrsubstr(col,0,4)字符串截取
AScol * 2 AS col_newcol取别名
统计(select)

对查找的rows需要按col分组统计的情况
select count(*),avg(col),col from table where col > 1 group by col

OperatorSQL Example解释
COUNT(*), COUNT(column)count(col)计数
MIN(column)min(col)最小值
MAX(column)max(col)最大值
AVG(column)avg(col)平均值
SUM(column)sum(col)求和
GROUP BYgroup by col,col2分组
HAVINGHAVING col>100分组后条件
子表(table)

一次select的结果rows作为下一次select的临时table才能得到最终结果:
select * from (select * from table where col > 1) as tmp where col < 1

OperatorSQL Example解释
(select -)as tmp(select -)as tmpselect结果做子表
in(select -)in(select -)select结果做条件
avg(select -)avg(select -)select结果做条件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值