准备工作,1.创建表
CREATE TABLE IF NOT EXISTS `users` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB CHARSET = utf8mb4; CREATE TABLE IF NOT EXISTS `applications` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `systemName` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB CHARSET = utf8mb4; CREATE TABLE IF NOT EXISTS `user_application` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `applicationId` INTEGER NOT NULL, `userId` INTEGER NOT NULL, `type` TINYINT, UNIQUE `user_application_applicationId_userId_unique` (`applicationId`, `userId`), PRIMARY KEY (`id`) ) ENGINE = InnoDB CHARSET = utf8mb4;
2.创建数据
INSERT INTO `users` (`name`) VALUES ('张三'),('李四'),('老王'),('小明'),('涛哥'); INSERT INTO `applications` (`systemName`) VALUES ('mac'),('windows'),('linux'),('android'),('qilin'); INSERT INTO `user_application` (`applicationId`,`userId`,`type`) VALUES (1,1,1),(2,1,2),(3,1,2),(2,2,1),(2,2,4);
3.使用多对多 关联查询... 一个用户可以有多个应用,一个应用对应多个用户
查询“张三”下应用:
SELECT users.id, users.name, user_application.type, applications.systemName FROM users LEFT JOIN (user_application `user_application` INNER JOIN applications `applications` ON user_application.applicationId = applications.id) ON users.id = user_application.userId WHERE users.name = '张三'
查询“windows”下用户:
SELECT applications.systemName, users.name, user_application.type FROM applications LEFT JOIN (user_application `user_application` INNER JOIN users `users` ON user_application.userId = users.id) ON applications.id = user_application.applicationId WHERE applications.systemName = 'windows'