《MySQL精通指南》一文掌握
发表时间: 2021-02-23 23:13
在terminal中连接mysql,输入以下指令:
USE crashhouses;SHOW DATABASES:SHOW TABLESSHOW COLUMNS FROM customers;SHOW STATUS
USE crashhouses;SHOW DATABASES:SHOW TABLESSHOW COLUMNS FROM customers;SHOW STATUS
SELECT name FROM products ORDER BY name; --排序SELECT name,id FROM products ORDER BY name,id; --选择多个列排序--DESC关键字只应用与其前面的列名,不能部分使用DESC。SELECT name FROM products ORDER BY name DESC,id; --指定降序--LIMIT 必须位于ORDER BY 之后
--ORDER BY 位于 WHERE 之后SELECT name,id FROM products WHERE name = 'lucky' ORDER BY id; -- WHERE 的操作符有>,=,<,!=,BETWEEN等-- NULL 空值检查SELECT id FROM customers WHERE email IS NULL;
SELECT id, price FROM productsWHERE id=1003 AND price<=10;SELECT id, price FROM productsWHERE id=1003 OR id=1000;-- 括号改变计算的次序SELECT id, price FROM productsWHERE (id=1003 or id=1000) AND price<=10;SELECT id, price FROM productsWHERE id IN(1003,1006);SELECT id, price FROM productsWHERE id NOT IN(1003,1006);
-- '%'表示任何字符出现任意次数;'_'只匹配单个字符SELECT name FROM productsWHERE name LIKE '_jet%';
-- '%'表示任何字符出现任意次数;'_'只匹配单个字符SELECT name FROM productsWHERE name LIKE '_jet%';
LIKE 匹配整个列,REGEXP在列值内匹配
具体规则参考正则式符号
SELECT name FROM productsWHERE name REGEXP '^jet.*';SELECT id*2+1 AS new_id,Concat(RTrim(name),'(',LTrim(country),')')AS vend_titleFROM vendersORDER BY name;
函数直接作用于选中列
具体的函数到用的时候再查找
SELECT id, name, COUNT(*) AS num_prodsFROM productsWHERE id>1001 AND id < 1003GROUP BY id, nameORDER BY id;
WHERE 过滤行,HAVING过滤组
HAVING 不使用别名
SELECT id, name, COUNT(*) AS num_prodsFROM productsWHERE id>1001 AND id < 1003GROUP BY id, nameHAVING COUNT(*)>= 3ORDER BY id;
顺序如下:SELECT,FROM, WHERE, GROUP BY, HAVING ,ORDER BY, LIMIT
可以将一个SELECT子句嵌套在另一个SELECT语句中。其中,列必须匹配,即具有相同的列数,可以使用多个列。
使用子查询不总是执行这种类型数据的最有效办法。可以使用连接表。
SELECT id FROM ordersWHERE num IN ( SELECT num FROM orderitems WHERE id ='TNT2');
SELECT vend_name, prod_name, prod_price FROM vendors ,productsWHERE vendors.vend_id = products.vend_id;
SELECT vend_name, prod_name, prod_priceFROM vendors INNER JOIN productsON vendors.vend_id = products.vend_id;
给使用的表起别名, 应用的时候运用别名。
SELECT p1.id,p1.name FROM products AS p1, products AS p2WHERE p1.id=p2.id AND p2.id='DTNTR';
LEFT INNER…ON, RIGHT INNER… ON
两个SELECT 语句间加上UNION
SELECT id FROM products WHERE id>1UNIONSELECT id FROM products WHERE id<1;
UNION ALL 返回所有匹配行,包含重复的行;默认UNION,重复的行会被取消
在建立TABLE的时候,FULLTEXT()的列就是为了进行全文本搜索;
Match()的值必须与FULLTEXT()定义中的相同;
SELECT note_text FROM productnotesWHERE Match(note_text) Against('rabbit');
SELECT note_text FROM productnotesWHERE Match(note_text) Against('rabbit')WITH QUERY EXPANSION;
SELECT note_text FROM productnotesWHERE Match(note_text) Against('rabbit' IN BOOLEAN MODE)
// 插入多个行INSERT INTO Customers(name,age)VALUES('lucky','18'),('Larry','23');//插入检索出的数据INSERT INTO Customers(name,age)SELECT(name,age) FROM CustomersOld;
可用来更新或清空指定的列
UPDATE customersSET name='lucky',age='18'WHERE id=1000;//删除指定的列UPDATE customersSET mail=NULL;
可用来删除指定的行或删除所有行
DELETE FROM custometsWHERE id=10000;//快速的删除所有行TRUNCATE TABLE cus