查询在数据库上创建表
CREATE TABLE `user` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL, `course` smallint(5) unsigned DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; CREATE TABLE `course` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB;
由于我们使用的是InnoDB表并且知道user.course和course.id相关,因此我们可以指定外键关系:
ALTER TABLE `user` ADD CONSTRAINT `FK_course` FOREIGN KEY (`course`) REFERENCES `course` (`id`) ON UPDATE CASCADE;
联接查询(内部联接)
SELECT user.name, course.name FROM `user` INNER JOIN `course` onuser.course= course.id;