Multi mysql database query (the connector, the external connector, subquery)

With two tables (a_table, b_table), and related fields a_table.a_id b_table.b_id to demonstrate what MySQL in connection outer join (left (outside) connection, the right (outside) connection, all (outside) connection).

MySQL version: Server version: 5.6.31 MySQL Community Server (GPL)

Database tables: a_table, b_table

Topic: inner join, a left join (left outer join), the right connection (right outer join), fully connected (full outer join)

Table:

   

En:

1. The cross-connect query (not substantially used - is the product obtained two tables) (when such a query will produce a Cartesian product)
Syntax: select * from A, B;
join query (2. keywords in inner join - inner may be omitted)
implicit within the connector: select * from A, B where condition;
show the connection: select * from A inner join B on condition;

执行语句为:select * from a_table a inner join b_table bon a.a_id = b.b_id;

Summary: When and only when the data in the two tables are in line with the conditions on the back, will be select it.

Left connection:

Outer join query (using keywords outer join - outer can be omitted)
left outer join: left outer join

语句:select * from a_table a left join b_table bon a.a_id = b.b_id;
Results of the:

Summary: When a query to left join the table to the left of the main keywords table, all the data in this table will check out, if this is not the right table data, then use NULL field.

Right outer join:

右外连接:right outer join
select * from A right outer join B on 条件;

语句:select * from a_table a right outer join b_table b on a.a_id = b.b_id;
执行结果:

总结:在查询的时候,会以right join 这个关键字右边的表为主,然后将符合条件的查询出来,左表中没有的字段,使用NULL进行补充

全连接(全外连接)

MySQL目前不支持此种方式,可以用其他方式替代解决。

子查询:

子查询:一条select语句结果作为另一条select语法一部分(查询条件,查询结果,表等)。

语法: select ....查询字段 ... from ... 表.. where ... 查询条件

#3 子查询, 查询“化妆品”分类上架商品详情
#隐式内连接
SELECT p.*
FROM products p , category c
WHERE p.category_id=c.cid AND c.cname = '化妆品';
#子查询
##作为查询条件
SELECT *
FROM products p
WHERE p.category_id =
(
SELECT c.cid FROM category c
WHERE c.cname='化妆品'
);
##作为另一张表
SELECT *
FROM products p ,
(SELECT * FROM category WHERE cname='化妆品') c
WHERE p.category_id = c.cid;

查询结果:

总结:可以将一条查询语句作为另外一个查询语句的条件和表,再次进行查询.

 

Guess you like

Origin www.cnblogs.com/qingmuchuanqi48/p/11130037.html