MySQL学习笔记DML部分(一)(二)(b站自学Mosh老师持续更新中)
本帖最后由 yukari123 于 2023-2-20 11:44 编辑DAY1:
SELECT * --
-- FROM customers
-- where customer_id=1
-- order by first_name
SELECT子句--选择指定列
加AS 新列名可以改名称
SELECT DISTINCT state
FROM sql_store.customers;
命令根据指定属性去除重复
例如:
SELECT name,unit_price,unit_price*1.1 AS 'new price'
FROM sql_store.products;
static/image/hrline/5.gif
WHERE子句--条件语句
运算符有:>=<!AND,OR,NOT
例如
SELECT * FROM sql_store.order_items
WHERE order_id=6 AND unit_price*quantity >30
IN 运算符:可以缩短语句,以下两个表达相等
WHERE id=6 AND id=8 AND id=0
WHEREid IN(6,8,0)
between and 运算符:和c一样,包含子集[]
LIKE运算符:%代表任意长短字符,_代表任意一个字符长度的字符
REGEXP运算符:正则表达式,^abc表示字符串的开头,abc$表示字符串结尾,a|b|c表示或者
'e'表示对应ge,ie,me也可以使用范围'e'
IS NULL运算符: 查询列表的空值
SELECT * FROM sql_store.orders
WHERE shipped_date IS NULL
static/image/hrline/5.gif
ORDER BY 子句--数据排序
DESC 表示降序
SELECT * FROM sql_store.customers
ORDER BY first_name DESC -- 倒序
ORDER BY state,first_name --多选排序
也可以这么写,但最好不要,影响独立性
SELECT state,first_name
FROM sql_store.customers
ORDER BY 1,2
static/image/hrline/5.gif
LIMI子句
limit 3表示取前三行
SELECT *
FROM sql_store.customers
LIMIT 6,3 -- 表示跳过前六行数据显示三行数据
static/image/hrline/1.gif
DAY 2
在多张表中检索:
内连接 INNER JOIN
SELECT order_id,orders.customer_id,first_name,last_name
FROM orders
INNER JOIN customers
ON orders.customer_id = customers.customer_id -- INNER可以省略
也可以这么简写
SELECT order_id,o.customer_id,first_name,last_name
FROM orders AS o -- AS可以省略
INNER JOIN customers c
ON o.customer_id = c.customer_id
跨数据库连接
关键词和内连接一样,需要注意 数据库.表名
自连接
和上面基本相同,需要注意的是要取不同的别名,还要给每列都加个别名
SELECT
e.employee_id,
e.first_name,
m.first_name AS manger
FROM employees e
JOIN employees m
ON e.reports_to=m.employee_id
多表连接
SELECT
o.order_id,
c.first_name,
os.name AS status
FROM orders o
JOIN customers c
ON o.customer_id=c.customer_id
JOIN order_statuses os
ON o.status=os.order_status_id
....
....
SELECT
c.name,
pm.name payment_method
FROM payments p
JOIN payment_methods pm
ON p.payment_method=pm.payment_method_id
JOIN clients c
ON p.client_id=c.client_id
复合连接条件
使用多个条件连接两个表格,语法是
SELECT
*
FROM
JOIN
ON
AND
外连接
LEFT JOIN 表示join左边的表记录全部返回
RIGHT JOIN 表示join右边的标记录全部返回
多表外连接
SELECT
o.order_date,
o.order_id,
c.first_name,
s.name shipper,
os.name status
FROM orders o
JOIN customers c
ON o.customer_id=c.customer_id
LEFT JOIN shippers s
ON o.shipper_id=s.shipper_id
JOIN order_statuses os
ON o.status=os.order_status_id
using子句
FROM orders o
JOIN customers c
ON -- o.customer_id=c.customer_id
USING(customer_id) --可以代替上句简化语句
自然连接
不加on 后面系统自动识别相同的值,但这种方法不受人为控制不推荐使用
交叉连接
只是组合没有意义
隐性连接
SELECT s.name shipper,p.name product
FROM shippers s,products p
显性连接
SELECT s.name shipper,p.name product
FROM shippers s
CROSS JOIN products p
联合
将两列不同条件的连接到一起
SELECT
...
...
'白银' type
FROM
WHERE 条件
UNION
SELECT
...
...
'黄金' type
FROM
WHERE 顶顶顶~ {:7_146:}
页:
[1]