mysql中括号的表达_MYSQL中常⽤的SQL语句MYSQL中常⽤的SQL语句
⼀、增删改查
1.新增
指定字段插⼊:
INSERT INTO (, , ) VALUES (, , );
不指定字段插⼊:
INSERT INTO VALUES (, , );
⼀次插⼊多条数据:
INSERT INTO VALUES (, , ), (, , );
INSERT INTO (, , ) VALUES (, , ), (, , );
将查询结果插⼊新表:
INSERT INTO SELECT * FROM ;
将查询部分字段插⼊新表:
mysql中delete语句INSERT INTO (, ) SELECT , FROM ;
复制表:
CREATE TABLE SELECT * FROM ;
2.删除
条件删除:
DELETE FROM WHERE = 3;
全部删除(⼀⾏⼀⾏删):
DELETE FROM ;
快删:
DROP TABLE IF EXISTS ;
3.修改
条件修改:
UPDATE SET = WHERE = 3;
全部修改:
UPDATE SET = ;
修改多个字段:
UPDATE SET = , = ;
使⼀列的值与另⼀列的值相等:
UPDATE SET = ;
4.查询
全量查询:
SELECT * FROM ;
去重查询某列:
SELECT DISTINCT , FROM ;
⽐较运算:
SELECT * FROM WHERE id >= 3;
IN:
SELECT * FROM WHERE id IN (1, 2, 3);
BETWEEN AND:
SELECT * FROM WHERE id BETWEEN 1 AND 3;
NOT NULL:
SELECT * FROM WHERE id IS NOT NULL;
AND / OR:
SELECT * FROM WHERE id = 3 AND name = 'ming';
模糊查询(%为通配符,_为匹配任意⼀个字符,[charlist]为字符列中的任意单个字符):SELECT * FROM WHERE LIKE '%';
正则匹配查询:
SELECT * FROM WHERE REGEXP '^[aeiou]|ok$';
起别名:
SELECT AS FROM ;
合并两张表并去除重复值:
SELECT FROM UNION SELECT FROM ;
合并两张表⾮去重:
SELECT FROM UNION ALL SELECT FROM ;
分组:
SELECT , , COUNT(), COUNT() FROM GROUP BY , ;
分组 + 条件:
SELECT * FROM GROUP BY HAVING COUNT(*) > 1;
排序查询,正序ASC,逆序DESC:
SELECT * FROM ORDER BY DESC;
限制查询,从索引m开始,限制查n条:
SELECT * FROM ORDER BY DESC LIMIT m n;
⼆、函数
1.聚合函数
统计符合条件的⾏数:
SELECT COUNT(*) FROM WHERE > 3;
统计列中⾮空⾏数:
SELECT COUNT() FROM ;
统计列中⾮重复⾮空⾏数:
SELECT COUNT(DISTINCT ) FROM ;
统计列中的最⼤值和最⼩值:
SELECT MAX() FROM ;
统计求和:
SELECT SUM() FROM ;
求平均值:
SELECT AVG() FROM ;
分组合并:
SELECT , GROUP_CONCAT() FROM GROUP BY ;
三、连表查询
内连接:
SELECT a.*, b.* FROM AS a INNER JOIN AS b ON a.id = b.id;
左连接:
SELECT a.*, b.* FROM AS a LEFT JOIN AS b ON a.id = b.id;
右连接:
SELECT a.*, b.* FROM AS a RIGHT JOIN AS b ON a.id = b.id;
⼦查询:
SELECT * FROM WHERE id IN (SELECT id FROM GROUP BY id HAVING COUNT(*) > 1);
四、常⽤场景
1.字符串替换:
UPDATE SET = REPLACE(, str1, str2)
2.根据某⼀列删除表中重复数据(保留id⼩的数据):
DELETE FROM WHERE id NOT IN (SELECT id FROM (SELECT MIN(id) AS id FROM GROUP BY ) AS t);
3.根据某⼀列删除表中重复数据(保留id⼤的数据):
DELETE FROM WHERE id NOT IN (SELECT id FROM (SELECT MAX(id) AS id FROM GROUP BY ) AS t);
4.三个表的连表查询:
SELECT * FROM ( AS a LEFT JOIN AS b ON a.id = b.id) LEFT JOIN AS c ON a.id = c.id;
5.排除某个表中的⼀列,查其他所有列:
SELECT GROUP_CONCAT( SEPARATOR ',') FROM information_schema.COLUMNS WHERE table_name = AND
column_name != ;
6.去掉某⼀列中的括号及内容:
UPDATE SET = REPLACE(, SUBSTRING(, LOCATE('(', ), LOCATE(')', )-LOCATE('(', )+1), '');
7.根据两个表的相同列更新另⼀个表中的另⼀列数据:
UPDATE AS A, AS B SET A. = B. WHERE A. = B.;
8.查询数据库中的表名及字段信息:
# 查询当前数据库
SELECT DATABASE();
# 查询当前数据库中的所有表名
SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_TYPE='BASE TABLE';
# 查询指定数据库中的所有表名
SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='' AND TABLE_TYPE='BASE TABLE';
# 查询指定数据库中指定表名的字段信息
SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='' and TABLE_NAME='';
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论