SQL查询栗子

一.条件查询

  1.模糊查询-运算符 LIKE

     通配符

        %  (一个或多个字符) 

        _  (一个字符)

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

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

-- 结果:查询city的值中以A或L或N开头的数据
SELECT * 
FROM Persons
WHERE City LIKE '[ALN]%'

-- %%默认为查询所有

  2.范围查询-运算符 BETWEEN 或 IN

SELECT * FROM
smartpromoterecord
where
-- 1到100之间
Amount BETWEEN 1 and 100 
-- 1或100 
-- Amount IN (1,100),如果是字符串串就两者一样

  3.分组查询

     (1)语句group by,它条件是having不是where

-- 结果:找第一条ordertype不同的数据
SELECT * FROM `smartcashier`
GROUP BY OrderType
-- HAVING amount>188,这句让上面的结果又少了几条

    (2)关键词distinct,仅仅列出不同的值

-- 和下面那个一样
SELECT
distinct CustomerID 
FROM
smartownership
WHERE
UserID=66

  4.数据量查询-函数count()

    count(*),count()是不包括null的数据的数量,count(distinct 参数)是过滤重复值的数量

-- 从结果中看数量(其实一般直接看就好)
SELECT count(*) 
FROM(
SELECT
UserID,CustomerID 
FROM
smartownership
WHERE
UserID=66
GROUP BY
CustomerID   
)
smartownership
SELECT count(*) 
FROM smarttriage
WHERE 
smarttriage.CreateTime>"2019-02-18 00:00:00
-- 看有多少种值,每个值的数据的数量是
-- 或者用count(distinct cashierid)
SELECT count(*) FROM smartpromoterecord GROUP BY smartpromoterecord.CashierID

   5.数据分页查询-语句 LIMIT

SELECT *
FROM smartcashier
-- 查询到第1条~第30条的数据
-- LIMIT 30
-- 查询到第31条~第40条的数据
LIMIT 30,10

 

二.关联查询

  1.语句 XX JOIN...ON

    内连接INNER JOIN...ON,

    左连接LEFT JOIN...ON,右连接RIGHT JOIN...ON,

    全外连接FULL JOIN...ON(没成功)

-- 比如odertype=3或5没有detail,所以用左连接
SELECT
*
FROM
smartcashier
LEFT JOIN smartcashierdetail ON smartcashier.ID = smartcashierdetail.CashierID
WHERE
smartcashier.CreateTime >= "2019-02-07 00:00:00"
ORDER BY
smartcashier.CreateTime ASC

   2.语句 SELECT

-- 这个没实践
select a.title,a.username,b.adddate 
from table a,(select max(adddate) adddate from table where table.title=a.title) b

 

三.子查询

SELECT 
name,mobile,'性别' 
FROM 
(
SELECT ID,name,Mobile,gender,
CASE gender
    when 1 THEN ''
    WHEN 2 THEN ''
    ELSE '你管我' END AS '性别'
from smartcustomer
ORDER BY ID DESC
LIMIT 3,5
)
-- 下面这行没有的话就会失败
AS result

 

 

四.其他

   1.函数

    (1)计算-sum(),avg(),max(),min()

select sum(Amount)
from smartcashier
where CreateTime>"2019-02-01 00:00:00"

    (2)count()  

    (3)当前时间-now()

   2.运算符

    >,>=,<,<=,<>,=

    AND,OR,IS NULL,IS NOT NULL

    LIKE,BETWEEN,IN

  3.别名-语句 AS

SELECT LastName AS Family, FirstName AS Name
FROM Persons

   4.语句 CASE...WHEN...

SELECT ID,name,Mobile,gender,
CASE gender
    when 1 THEN ''
    WHEN 2 THEN ''
    ELSE '你管我' END AS '性别'
from smartcustomer
ORDER BY ID DESC
LIMIT 3,5
posted @ 2019-02-18 13:54  margot921  阅读(121)  评论(0编辑  收藏  举报