mysql 03

2021/8/3 19:06:04

本文主要是介绍mysql 03,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

多表查询:通过cust_id 在customers和orders表中查询信息

SELECT cust_id,COUNT(cust_id),(SELECT cust_name from customers where customers.cust_id = orders.cust_id)
from orders
GROUP BY cust_id

 

 

inner join(查询多个表的交集,共有的内容)

多个表查询的时候

主要语法

inner join 表 on -----表之间的关系语句

-- INNER JOIN 表 ON +有关联部分 -------- 两个表关系

 

select * from teacher(第一个表名)

INNER JOIN course(第二个表名)

ON teacher.id = course.teacher_id  ------两个表之间有关联部分

 

 

SELECT name,course_name FROM teacher

INNER JOIN course

ON teacher.id = course.teacher_id

 

 

-- 三个表之间关联

SELECT name,course_name FROM student(第一个表名)

INNER JOIN student_course(第二个表名)

ON student.id = student_course.student_id(如果两个表中有多个条件是关联的,后面+and连接另外的关联条件)

INNER JOIN course(第三个表名)

ON course.id = student_course.course_id

 

 

左连接

left join +表名 on +相同部分

以左表为主,左表的数据都会显示。想以哪个表为左表,就放在第一行命令的from后,左表信息全部显示,其他表如果没有内容的话就显示为null

SELECT vendors.vend_id,vend_name,prod_name from vendors -- 左表

LEFT JOIN products

ON products.vend_id = vendors.vend_id

多个表左连接也是一样,在第三个表前面再加left join

Union

-- union 在连接两个表的时候如果数据有相同,会自动去重,但是如果用union all 连接,就不会去重

SELECT age FROM student

UNION

SELECT age from teacher;

 



这篇关于mysql 03的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程