MySQL JOIN 连接查询

语法

SELECT * FROM table1 [INNER|INNER|RIGHT] JOIN table2 ON table1.id = table2.id;

INNER查询等号两边都存在的数据,INNER为缺省值
LEFT连接,查询等号左边存在的数据
RIGHT连接,查询等号右边存在的数据

例子

//结构
CREATE TABLE `user`  (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(10) NOT NULL,
  `sex` tinyint(4) NOT NULL,
  `class_id` tinyint(4) NOT NULL,
  `tel` char(11) NOT NULL,
  PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARACTER SET utf8;

CREATE TABLE `class`  (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARACTER SET utf8;

//INNER连接
SELECT
    `user`.`name` AS 'name',
    `class`.`name` AS 'class'
FROM
    `class` INNER JOIN `user` ON `class`.`id` = `user`.`class_id`;

//等价INNER连接的写法
SELECT 
    `user`.`name` AS 'name',
    `class`.`name` AS 'class'
FROM
    `user`,`class`
WHERE
    `class`.`id` = `user`.`class_id`;

你可能感兴趣的:(MySQL JOIN 连接查询)