该篇是阅读MySql 5.1 参考手册做的笔记,链接如:http://www.matools.com/api/mysql。
create database 数据库名;
use 数据库名;
show databases;
show tables;
CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);
describe 表名
insert into pet values ('Puffball','Diane','hamster','f','1999-03-30',NULL);
SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy;
select * from pet
SELECT * FROM pet WHERE name = 'Bowser'
字符串比较不区分大小写。
select name, birth from pet
select name, birth from pet order by birth
默认会按照升序进行排序,升序ASC
,降序DESC
。
可以使用BINARY强制执行区分大小写的分类功能,如:ORDER BY BINARY col_name.
多个列排序,如下:ORDER BY species, birth DESC;
。
注意DESC
关键字仅适用于在它前面的列名(birth
);不影响species
列的排序顺序。
update set birth = '1989-08-31' where name = 'Bowser'
SELECT name, birth, CURDATE(), (YEAR(CURDATE())-YEAR(birth)) - (RIGHT(CURDATE(),5)
YEAR()提取日期的年部分;
RIGHT()提取日期的MM-DD (日历年)部分的最右面5个字符;
查询下个月出生的宠物
SELECT name, birth FROM pet WHERE MONTH(birth) = MONTH(DATE_ADD(CURDATE(),INTERVAL 1 MONTH));
NULL判断,查找是NULL和不是NULL的语句如下:birth is NULL
, birth is not NULL
。
group by
中 两个 null 视为相同。
MySql中 NULL
是最大的值。
在MySql中,“_”
匹配任何单个字符,而 “%”
匹配任意数目字符(包括零字符),使用 LIKE
或 NOT LIKE
比较操作符。
SELECT COUNT(*) FROM pet;
SELECT owner, COUNT(*) FROM pet GROUP BY owner;
select database()
SELECT article, MAX(price) AS price
FROM shop
GROUP BY article
SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE s1.article = s2.article);
SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;
SELECT * FROM shop WHERE price=@min_price OR price=@max_price;
INSERT INTO pet
VALUES('Fluffy','Harold','cat','f','1993-02-04',NULL),
('Claws','Gwen','cat','m','1994-03-17',NULL),
('Buffy','Harold','dog','f','1989-05-13',NULL),
('Fang','Benny','dog','m','1990-08-27',NULL),
('Bowser','Diane','dog','m','1979-08-31','1995-07-29 '),
('Chirpy','Gwen','bird','f','1998-09-11',NULL),
('Whistler','Gwen','bird',NULL ,'1997-12-09',NULL),
('Slim','Benny','snake','m','1996-04-29',NULL),
('Puffball','Diane','hamster','f','1999-03-30',NULL)