0
点赞
收藏
分享

微信扫一扫

MySQL数据库查询数据操作篇第二十一篇连接查询


21.连接查询(单独一篇)
mysql> create table suppliers
-> (
-> s_id int not null auto_increment,
-> sname char(50) not null,
-> s_city char(50) null,
-> s_zip char(50) not null,
-> s_call char(50) not null,
-> primary key (s_id)
-> );
Query OK, 0 rows affected

mysql> insert into suppliers(s_id,sname,s_city,s_zip,s_call)
-> values(1001,"fastfruit inc","tianjing","30000","48075"),
-> (1002,"lt supplies","chongqing","40000","44332"),
-> (1003,"acme","shanghai","25809","90046"),
-> (1004,"good boy","anqing","528437","11123"),
-> (1005,"oldboy","hefei","246100","33322")
-> ;
Query OK, 5 rows affected
Records: 5 Duplicates: 0 Warnings: 0
查询之前,查看两表的结构:
mysql> desc fruits;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| f_id | char(10) | NO | PRI | NULL | |
| s_id | int(11) | NO | | NULL | |
| f_name | char(255) | NO | | NULL | |
| f_price | varchar(11) | NO | | NULL | |
+---------+-------------+------+-----+---------+-------+
4 rows in set

mysql> desc suppliers;
+--------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+----------------+
| s_id | int(11) | NO | PRI | NULL | auto_increment |
| sname | char(50) | NO | | NULL | |
| s_city | char(50) | YES | | NULL | |
| s_zip | char(50) | NO | | NULL | |
| s_call | char(50) | NO | | NULL | |
+--------+----------+------+-----+---------+----------------+
5 rows in set

由结果可以看到,fruits表和suppliers表中都有相同数据类型的字段s_id。两个表通过s_id字段建立联系。接下来从fruits表中查询f_name,f_price字段,从suppliers表中查询s_id,s_name:
mysql> select suppliers.s_id,sname,f_name,f_price
-> from fruits,suppliers
-> where fruits.s_id = suppliers.s_id;
Empty set

在fruits表和suppliers表之间,使用inner join 语法进行内连接查询:
mysql> select suppliers.s_id,sname,f_name,f_price
-> from fruits inner join suppliers
-> on fruits.s_id = suppliers.s_id;
Empty set


mysql> create table orders
-> (
-> o_num int not null auto_increment,
-> o_date datetime not null,
-> c_id int not null,
-> primary key (o_num)
-> );
Query OK, 0 rows affected
mysql> insert into orders(o_num,o_date,c_id)
-> values(3001,"2019-12-11",1001),
-> (3002,"2019-12-12",1002),
-> (3003,"2019-12-13",1003)
-> ;
Query OK, 3 rows affected
Records: 3 Duplicates: 0 Warnings: 0

左连接:
mysql> select customers.c_id,orders.o_num
-> from customers left outer join orders
-> on customers.c_id = orders.c_id
-> ;
+-------+-------+
| c_id | o_num |
+-------+-------+
| 10086 | NULL |
| 10087 | NULL |
| 10088 | NULL |
+-------+-------+
3 rows in set

mysql> select suppliers.s_id,sname,f_name,f_price
-> from fruits inner join suppliers
-> on fruits.s_id = suppliers.s_id
-> order by fruits.s_id;
Empty set



举报

相关推荐

0 条评论