runoops.com

数据库中CROSS JOIN 和INNER JOIN 用法上的区别

先看MySQL的两张表:

runoops_tbl:

tcount_tbl:

本章节使用的数据库结构及数据下载:runoops-join-test.sql

JOIN 按照功能大致分为如下三类:

INNER JOIN(内连接,或等值连接):取得两个表中存在连接匹配关系的记录。

LEFT JOIN(左连接):取得左表(table1)完全记录,即是右表(table2)并无对应匹配记录。

RIGHT JOIN(右连接):与 LEFT JOIN 相反,取得右表(table2)完全记录,即是左表(table1)并无匹配对应记录。

具体参考另外文章:MySQL JOIN 连接

注意:mysql不支持Full join,不过可以通过UNION 关键字来合并 LEFT JOIN 与 RIGHT JOIN来模拟FULL join。

这里讲下交叉连接,及 CROSS JOIN

在 MySQL 中(仅限于 MySQL) CROSS JOIN 与 INNER JOIN 的表现是一样的,在不指定 ON 条件得到的结果都是笛卡尔积,反之取得两个表完全匹配的结果。INNER JOIN 与 CROSS JOIN 可以省略 INNER 或 CROSS 关键字,因此下面的 SQL 效果是一样的。

CROSS JOIN:

-- CROSS JOIN
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	CROSS JOIN tcount_tbl b;

-- INNER JOIN	
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	INNER JOIN tcount_tbl b;

-- JOIN	
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	JOIN tcount_tbl b;	

结果都是:

CROSS JOIN ON:

-- CROSS JOIN ON
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	CROSS JOIN tcount_tbl b 
	ON a.runoops_author = b.runoops_author;

-- INNER JOIN ON
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	INNER JOIN tcount_tbl b
	ON a.runoops_author = b.runoops_author;

-- JOIN	ON
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	JOIN tcount_tbl b
	ON a.runoops_author = b.runoops_author;

结果都是:

注意:SQL Server 中只能用CROSS JOIN,不能用INNER JOIN 或INNER,但可以用 WHERE 过滤:

-- SQL Server CROSS JOIN 正确用法
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	CROSS JOIN tcount_tbl b;

-- SQL Server CROSS JOIN 可以用 WHERE 过滤
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	CROSS JOIN tcount_tbl b
	WHERE a.runoops_author = b.runoops_author;

-- SQL Server CROSS JOIN 错误用法
SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	INNER JOIN tcount_tbl b;

SELECT
	a.runoops_id,
	a.runoops_author,
	b.runoops_count 
FROM
	runoops_tbl a
	JOIN tcount_tbl b;

Captcha Code

0 笔记

分享笔记

Inline Feedbacks
View all notes