SHOW DATABASES;
USE databaseName;
SHOW TABLES;
SHOW COLUMNS FROM tableName;
SHOW STATUS;
SHOW CREATE DATABASE databaseName;
SHOW CREATE TABLE tableName;
SHOW GRANTS;
SHOW ERRORS;
SHOW WARNINGS;
SELECT DISTINCT `name` FROM `user`;
SELECT id,`name` FROM `user` WHERE name REGEXP '正则表达式';
示例:将小写转换成大写
SELECT `name`,UPPER(name) AS upper_name FROM `user` WHERE id = 1;
函数 | 说明 |
---|---|
LEFT(str,len) | 返回串左边的字符 |
RIGHT(str,len) | 返回串右边的字符 |
LOCATE(substr,str) | 找出串的一个子串 |
LOWER(str) | 将串转换成小写 |
UPPER(str)) | 将串转换成大写 |
LTRIM(str) | 去掉串左边的空格 |
RTRIM(str) | 去掉串右边的空格 |
LENGTH(str) | 返回串的长度 |
SOUNDEX(str) | 返回串的SOUNDEX值 |
SUBSTRING(str FROM pos FOR len) | 返回字串的字符 |
SELECT CONCAT(name,'(',id,')') FROM `user` WHERE id = 1;
CREATE TABLE customers(
cust_id int NOT NULL AUTO_INCREMENT,
cust_name VARCHAR(50) NULL,
cust_address VARCHAR(50) NULL,
cust_city VARCHAR(50) NULL,
PRIMARY KEY(cust_id)
)ENGINE=INNODB
CREATE VIEW user_view AS SELECT name FROM `user`
SELECT name FROM user_view
值得注意的是,存储过程入参和出参不能和表字段名重复,有可能会造成不能查出数据,并且出参不能带下划线。
//创建存储过程不带参数
CREATE PROCEDURE user_pro()
BEGIN
SELECT name FROM `user`;
END
//调用存储过程
CALL user_pro();
//创建存储过程带入参(pro_id)和出参(username)
CREATE PROCEDURE user_procedure(IN pro_id int,
OUT username VARCHAR(10))
BEGIN
SELECT name FROM `user` WHERE id = pro_id
INTO username;
END
//存储过程调用
CALL user_procedure(1,@username);
SELECT @username;
SHOW CREATE PROCEDURE user_procedure;
CREATE USER username IDENTIFIED BY '123456789';
RENAME USER username TO username2;
DROP USER username2;
// crashcourse.*表示数据库上的所有表
GRANT SELECT,DELETE ON crashcourse.* TO username;
SHOW GRANTS FOR username;
REVOKE DELETE ON crashcourse.* FROM username;
SET PASSWORD FOR username = PASSWORD('123456789');
SET PASSWORD = PASSWORD('123456789');
TRUNCATE TABLE tableName;
DROP TABLE tableName;
DROP VIEW user_view;
DROP PROCEDURE user_pro;
CREATE DEFINER=`root`@`%` FUNCTION `getDeptnameByUserId`(`userId` int) RETURNS varchar(50) CHARSET utf8
BEGIN
DECLARE v_name VARCHAR(50);
SELECT username INTO v_name FROM sys_user WHERE user_id = userId;
RETURN v_name;
END
SELECT user_id ,getDeptnameByUserId(user_id) AS username FROM sys_user WHERE user_id = 1
DROP FUNCTION getDeptnameByUserId