Home  >  Article  >  Database  >  mysql中关联查询sql 语句

mysql中关联查询sql 语句

WBOY
WBOYOriginal
2016-06-07 17:51:411295browse

关联子查询是指一个包含对表的引用的子查询,该表也显示在外部查询中。通俗一点来讲,就是子查询引用到了主查询的数据数据。

 以一个实际的例子来理解关联子查询


left join   :左连接,返回左表中所有的记录以及右表中连接字段相等的记录。
right join :右连接,返回右表中所有的记录以及左表中连接字段相等的记录。
inner join: 内连接,又叫等值连接,只返回两个表中连接字段相等的行。
full join:外连接,返回两个表中的行:left join + right join
cross join:结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数。

 代码如下 复制代码

declare @a table(a int,b int)
declare @b table(a int,b int)

insert @a values(1,1)
insert @a values(2,2)
insert @b values(1,1)
insert @b values(3,3)
* from @a
select * from @b
--左:
select * from @a Aa left join @b Bb on Aa.a=Bb.a
--右:
select * from @a Aa right join @b Bb on Aa.a=Bb.a
--内
select * from @a Aa inner join @b Bb on Aa.a=Bb.a
--外:
select * from @a Aa full join @b Bb on Aa.a=Bb.a
--交叉连接
select * from @a  cross join @b

关联子查询效率
很明显,一般情况下关联子查询的效率是比较低下的,实际上本例中的关联子查询例子也仅是为了演示关联子查询的原理及用法。如果可以的话,关联子查询尽量使用 JOIN 或其他查询来代替。如本例中,使用 INNER JOIN 来替换的 SQL 为:

 代码如下 复制代码
SELECT article.* FROM article INNER JOIN user ON article.uid = user.uid

注意:此处只是为了演示用 INNER JOIN 替换关联子查询的样例,并非表名这种处理是最优处理

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn