SQL干货 增删改查(CURD)从入门到熟练 实用 - lbx

一、基本操作

1、添加(insert)

INSERT INTO user_temp (uid, username) VALUES (19088, 'asdf');

2、修改(update)

UPDATE user_temp SET username = '111' WHERE uid = 19088;

3、删除(delete)

DELETE FROM user_temp whe uid = 19088;

4、查询(select)

SELECT id,username,spreader_uid,addtime FROM rrl_user WHERE addtime >= '2018/08/26';

二、SQL进阶

1、批量添加,INSERT INTO SELECT语句与SELECT INTO FROM语句区别

(1)INSERT INTO SELECT
Insert into Table2(field1,field2) select value1,value2 from Table1;

注:1.要求目标表Table2必须存在,并且字段field1,field2 也必须存在
2.如果Table2有主键而且不为空,则 field1,field2中必须包括主键

(2)SELECT INTO FROM
SELECT vale1, value2 into Table2 from Table1

注:1.要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中


2、批量修改,根据一张表的数据批量修改另一张表的数据

UPDATE
    rrl_goods
SET
    beans_pay_rate = beans,
    cash_pay_rate = cash
FROM rrl_goods, test_goods_20180705
WHERE test_goods_20180705.goods_id = rrl_goods.id

注:beans_pay_rate 和 cash_pay_rate 是表 rrl_goods 的字段,beans 和 cash 是表 test_goods_20180705 的字段


3、批量删除

(1)子查询删除
--删除所有满足子查询的数据
DELETE FROM user_temp whe uid IN (SELECT id FROM rrl_user WHERE addtime >= '2018/08/26');
(2)删除重复记录
delete from tablename where id not in (select max(id) from tablename group by col1,col2,...);

4、查询进阶

(1)子查询方式1(IN或者=)
SELECT
    *
FROM
    rrl_user_money_record 
WHERE uid IN (
    SELECT id 
    FROM rrl_user 
    WHERE 
    addtime >= '2018/08/26'
);
(2)子查询方式2
SELECT
    *,
    (SELECT username FROM rrl_user WHERE id = uid) as username
FROM
    rrl_user_money_record 
WHERE uid = 19088;
(3)连接查询-左连接
SELECT
    r.*,u.username,u.addtime
FROM
    rrl_user_money_record r
LEFT JOIN rrl_user u
ON r.uid = u.id
WHERE u.addtime >= '2018/08/26';

左连接以左表数据为基准。

(4)连接查询-右连接
SELECT
    r.*,u.username,u.addtime
FROM
    rrl_user_money_record r
RIGHT JOIN rrl_user u
ON r.uid = u.id
WHERE u.addtime >= '2018/08/26';

右连接以右表数据为基准。

(5)连接查询-全连接
SELECT
    r.*,u.username,u.addtime
FROM
    rrl_user_money_record r
JOIN rrl_user u
ON r.uid = u.id
WHERE u.addtime >= '2018/08/26';

全连接以两表数据为基准。

(6)偏移分页查询(OFFSET-FETCH)
SELECT
    *
FROM
    rrl_user
ORDER BY
    addtime DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

注:偏移0行去10行,即显示第一页,每页10条数据。

SELECT
    *
FROM
    rrl_user
ORDER BY
    addtime DESC
OFFSET XXX ROWS FETCH NEXT {PageSize} ROWS ONLY;

注: XXX = (PageIndex - 1) * PageSize

(7)分组查询(可以去重)
SELECT
    uid,
    COUNT(1) c
FROM
    rrl_user_money_record 
WHERE addtime >= '2018/08/26'
GROUP BY uid
HAVING COUNT(1) > 1;

注: GROUP BY 后的字段必须在SELECT后面查询出来才行,分组查询也达到去重的目的。

(8)去重查询
SELECT
    DISTINCT uid
FROM
    rrl_user_money_record 
WHERE addtime >= '2018/08/26';
(9)随机取出10条数据查询
select top 10 * from rrl_user order by newid();

你可能感兴趣的:(SQL)