本文共 2082 字,大约阅读时间需要 6 分钟。
JOIN是SQL中用于将两个或多个表的数据结合的操作,常见的JOIN类型包括INNER JOIN、LEFT JOIN、RIGHT JOIN和FULL JOIN等。通过不同的JOIN类型,可以实现不同的数据组合效果。
INNER JOIN的特点是只有当两个表中存在匹配记录时,才会返回结果。如果一个表中没有匹配的数据,结果表中也不会有对应的行。
LEFT JOIN(左连接)则相反,即使右表中没有匹配的数据,左表的所有记录都会被保留并返回。这意味着左表的所有数据都会出现在结果中。
RIGHT JOIN(右连接)则是左连接的对立操作。即使左表中没有匹配的数据,右表的所有记录也会被保留并返回。
FULL JOIN(全连接)则更加灵活。只要有一个表存在匹配记录,就会返回结果。与INNER JOIN不同,FULL JOIN不会因为匹配失败而舍弃任何一边的数据。
LEFT JOIN和RIGHT JOIN在处理缺失值时有明显区别。LEFT JOIN会优先保留左表的记录,而RIGHT JOIN则优先保留右表的记录。
以下是基于上述数据库的具体操作示例:
create database if not exists test default charset utf8 collate utf8_general_ci;use test;set names utf8;set foreign_key_checks = 0;drop table if exists Websites;create table Websites ( id int(11) not null, name char(20) not null default '', url char(30) not null default '', alexa int(11) not null, country char(10) not null default '', primary key (id)) engine=InnoDB default charset=utf8;drop table if exists access_log;create table access_log ( aid int(11) not null, site_id int(11) not null, count int(11) not null, date datetime not null) engine=InnoDB default charset=utf8;insert into Websites values ('1', 'Google', 'https://www.google.cm/', '1', 'USA');insert into Websites values ('2', 'TaoBao', 'https://www.taobao.cm/', '13', 'CN');insert into Websites values ('3', 'CaiNiao', 'https://www.runoob.cm/', '4689', 'CN');insert into Websites values ('4', 'Weibo', 'https://www.weibo.cm/', '20', 'CN');insert into Websites values ('5', 'Facebook', 'https://www.facebook.cm/', '3', 'USA');insert into Websites values ('7', 'stackoverflow', 'https://www.stackoverflow.cm/', '0', 'IND'); 以下是一个使用INNER JOIN的查询示例:
select Websites.id, Websites.name, access_log.count, access_log.datefrom Websites inner join access_logon Websites.id = access_log.site_id;
该查询会返回以下数据:
| id | name | count | date |
|---|---|---|---|
| 1 | 45 | 2016-05-10 | |
| 2 | TaoBao | 100 | 2016-05-13 |
| 3 | CaiNiao | 230 | 2016-05-14 |
| 4 | 10 | 2016-05-14 | |
| 5 | 205 | 2016-05-14 | |
| 6 | stackoverflow | 220 | 2016-05-15 |
通过上述查询,可以清晰地看到Websites表和access_log表之间的关联。
转载地址:http://xntx.baihongyu.com/