内连接查询
创建suppliers
-- 创建suppliers CREATE TABLE suppliers ( s_id int not null auto_increment, s_name char(50) not null, s_city char(50) null, s_zip char(10) null, s_call char(50) not null, primary key (s_id) );
创建fruits
-- 创建fruits CREATE TABLE fruits ( f_id CHAR(10) not null, s_id int not null, f_name CHAR(255) not NULL, f_price DECIMAL(8,2) not NULL, PRIMARY KEY(f_id) );
两张表都有s_id字段
INSERT into suppliers (s_id,s_name,s_city,s_zip,s_call) VALUES (101,‘FastFruit Inc‘,‘Tianjin‘,‘300000‘,‘48075‘), (102,‘LT Supplies‘,‘chongqing‘,‘400000‘,‘44333‘), (103,‘ACME‘,‘Shanghai‘,‘20000‘,‘90046‘), (104,‘FNK Inc‘,‘Zhongshan‘,‘528437‘,‘11111‘), (105,‘Good Set‘,‘Taiyuang‘,‘030000‘,‘22222‘), (106,‘just Eat Ours‘,‘Beijing‘,‘010‘,‘45678‘), (107,‘DK Inc‘,‘Zhengzhou‘,‘450000‘,‘33332‘);
INSERT INTO fruits (f_id,s_id,f_name,f_price) VALUES (‘a1‘,101,‘apple‘,5.2), (‘b1‘,101,‘blackberry‘,10.2), (‘bs1‘,102,‘orange‘,11.2), (‘bs2‘,105,‘melon‘,8.2), (‘t1‘,102,‘banana‘,10.3), (‘t2‘,102,‘grape‘,5.3), (‘o2‘,103,‘cocount‘,9.2), (‘co‘,101,‘cherry‘,3.2), (‘a2‘,103,‘apricot‘,2.2), (‘l2‘,104,‘lemon‘,6.4), (‘b2‘,104,‘berry‘,7.6), (‘m1‘,106,‘mango‘,16.5), (‘m2‘,105,‘xbabay‘,2.6), (‘t4‘,107,‘xbababa‘,3.6), (‘m3‘,105,‘xxtt‘,11.6), (‘b5‘,107,‘xxxx‘,3.6)
SELECT f_id,suppliers.s_id,fruits.s_id,s_name,f_name,f_price from fruits,suppliers where fruits.s_id=suppliers.s_id
使用内连接
SELECT f_id,suppliers.s_id,fruits.s_id,s_name,f_name,f_price from fruits INNER JOIN suppliers on fruits.s_id=suppliers.s_id
最终结果和上面的查询结果一模一样.
使用where子句定义连接条件比较简单明了,而inner join 语法是ansi sql的标准规范,使用inner join 连接语法能够确保
不会忘记连接条件,而且,where子句在某些时候会影响查询的性能.
自连接查询
如果在一个连接查询中,涉及到的两个表都是同一个表,这种查询称为自连接查询.自连接是一种特殊的内连接,
它是之相互连接的表在物理上为同一张表,但可以在逻辑上分为两张表.
查看f_id=‘a1‘的水果供应商提供其他水果种类
SELECT f1.f_id,f1.f_name,f1.s_id,f2.s_id,f2.f_id,f2.f_name from fruits as f1,fruits as f2 where f1.s_id=f2.s_id and f2.f_id=‘a1‘;
上面的意思可以用这个sql语句表示
SELECT * from fruits where s_id=101
外连接查询
外连接查询分为左外连接和又外连接
left join(左连接):返回包括左表中的所有记录和右表中连接字段相等的记录
right join(右连接):返回包括右表中的所有记录和右表中连接字段相等的记录.
-- 创建表customers CREATE TABLE customers ( c_id int not null auto_increment, c_name CHAR(50) not NULL, c_address CHAR(50) NULL, c_city CHAR(50) NULL, c_zip CHAR(50) NULL, c_contact CHAR(50) NULL, c_email CHAR(255) NULL, PRIMARY KEY(c_id) );
插入数据:
-- 插入数据 insert into customers (c_id,c_name,c_address,c_city,c_zip,c_contact,c_email) VALUES (10001,‘RedHook‘,‘200 Street‘,‘Tianjin‘,‘300000‘,‘LiMing‘,‘LMing@163.com‘), (10002,‘Stars‘,‘333 Fromage Lane‘,‘Dalian‘,‘116000‘,‘Zhangbo‘,‘jerry@hotmail.com‘), (10003,‘Nethood‘,‘1 Sunny Place‘,‘Qingdao‘,‘266000‘,‘LuoCong‘,null), (10004,‘JOTO‘,‘829 Riverside Drive‘,‘Haikou‘,‘570000‘,‘YangShan‘,‘sam@hotmail.com‘);
204页待续..........
原文:http://www.cnblogs.com/guoyansi19900907/p/4934517.html