mysql數據庫中實現內鏈接、左鏈接、右鏈接

原文:http://www.cnblogs.com/xwdreamer/archive/2010/12/15/2297058.htmlhtml

 

內鏈接:把兩個表中數據對應的數據查出來 
外鏈接:以某個表爲基礎把對應數據查出來mysql

首先建立數據庫中的表,數據庫代碼以下:sql

 

/*
Navicat MySQL Data Transfer
Source Server         : localhost_3306
Source Server Version : 50150
Source Host           : localhost:3306
Source Database       : store
Target Server Type    : MYSQL
Target Server Version : 50150
File Encoding         : 65001
Date: 2010-12-15 16:27:53
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `grade`
-- ----------------------------
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade` (
  `no` int(11) NOT NULL AUTO_INCREMENT,
  `grade` int(11) NOT NULL,
  PRIMARY KEY (`no`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of grade
-- ----------------------------
INSERT INTO grade VALUES ('1', '90');
INSERT INTO grade VALUES ('2', '80');
INSERT INTO grade VALUES ('3', '70');
-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `no` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`no`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO student VALUES ('1', 'a');
INSERT INTO student VALUES ('2', 'b');
INSERT INTO student VALUES ('3', 'c');
INSERT INTO student VALUES ('4', 'd');

student表中的字段分別是no和name,grade表中的字段是no和grade。兩張表中的no都表明的是學生的學號。數據庫

查詢student表的結果:spa

mysql> select * from grade;
+----+-------+
| no | grade |
+----+-------+
|  1 |    90 |
|  2 |    80 |
|  3 |    70 |
+----+-------+
rows in set

查詢grade表的結果:code

mysql> select * from student s inner join grade g on s.no=g.no;
 
+----+------+----+-------+
| no | name | no | grade |
+----+------+----+-------+
|  1 | a    |  1 |    90 |
|  2 | b    |  2 |    80 |
|  3 | c    |  3 |    70 |
+----+------+----+-------+
rows in set

左鏈接(左表中全部數據,右表中對應數據) htm

mysql> select * from student as s left join grade as 
g on s.no=g.no; 
+----+------+------+-------+
| no | name | no   | grade |
+----+------+------+-------+
|  1 | a    |    1 |    90 |
|  2 | b    |    2 |    80 |
|  3 | c    |    3 |    70 |
|  4 | d    | NULL | NULL  |
+----+------+------+-------+
rows in set

右鏈接(右表中全部數據,左表中對應數據) blog

mysql> select * from student as s right
 join grade as g on s.no=g.no; 
+----+------+----+-------+
| no | name | no | grade |
+----+------+----+-------+
|  1 | a    |  1 |    90 |
|  2 | b    |  2 |    80 |
|  3 | c    |  3 |    70 |
+----+------+----+-------+
rows in set
相關文章
相關標籤/搜索