SQL:MySQL7种JOIN用法总结
  TEZNKK3IfmPf 2023年11月14日 19 0

 

SQL:MySQL7种JOIN用法总结

数据准备

1、建2张表

# 姓名表
create table table_name(
id int(11) primary key auto_increment,
user_id int(11) default 0,
name varchar(5) default ''
);

# 年龄表
create table table_age(
id int(11) primary key auto_increment,
user_id int(11) default 0,
age int(11) default 0
);

2、原始数据

# user_id, name, age
(1, "小赵", 21),
(2, "小钱", 22),
(3, "小孙", 23),

将6条数据分为两部分插入到数据库

# 名字表少一条 user_id = 3
insert into table_name(user_id, name)
values(1, "小赵"), (2, "小钱");

# 年龄表少一条 user_id = 2
insert into table_age(user_id, age)
values(1, 21), (3, 23);

3、查看数据

mysql> select * from table_name;
+----+---------+--------+
| id | user_id | name |
+----+---------+--------+
| 1 | 1 | 小赵 |
| 2 | 2 | 小钱 |
+----+---------+--------+

mysql> select * from table_age;
+----+---------+------+
| id | user_id | age |
+----+---------+------+
| 1 | 1 | 21 |
| 3 | 3 | 23 |
+----+---------+------+

1、INNER JOIN(内连接)

SQL:MySQL7种JOIN用法总结

mysql> select a.user_id, name, age  
-> from table_name as a inner join table_age as b
-> on a.user_id=b.user_id;

+---------+--------+------+
| user_id | name | age |
+---------+--------+------+
| 1 | 小赵 | 21 |
+---------+--------+------+
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   27   0   0 mysql
  TEZNKK3IfmPf   2024年05月17日   54   0   0 sqlmysql
  TEZNKK3IfmPf   2024年05月31日   31   0   0 数据库mysql
  TEZNKK3IfmPf   2024年05月17日   38   0   0 sqlcube
  TEZNKK3IfmPf   2024年05月17日   50   0   0 jsonmysql
  TEZNKK3IfmPf   2024年05月17日   51   0   0 mysqlphp
  TEZNKK3IfmPf   2024年05月31日   27   0   0 数据库mysql
TEZNKK3IfmPf