myBatis實現多對多操作的sql語句

2021-10-17 05:09:37 字數 3348 閱讀 6896

實現角色對人的多對多查詢,將有角色的人篩選出來:

/*實現角色對人的多對多查詢*/

實現人對角色的多對多查詢,將所有使用者都列出來,有角色顯示角色資訊,沒有顯示null:

/*實現人對角色的多對多查詢*/

select u.

*,r.id as rid,r.role_name,r.role_desc from user u

left outer join user_role ur on ur.uid=u.id

left outer join role r on ur.rid=r.id

該處使用的url網路請求的資料。

sql檔案:

drop table if exists `user`;

create table `user` (

`id` int(11

) not null auto_increment,

`username` varchar(32

) not null comment '使用者名稱'

, `birthday` datetime default null comment '生日'

, `***` char(1

) default null comment '性別'

, `address` varchar

(256

) default null comment '位址'

, primary key (`id`)

) engine=innodb default charset=utf8;

insert into `user`(`id`,`username`,`birthday`,`***`,`address`) values (41,

'老王'

,'2018-02-27 17:47:08'

,'男'

,'北京'),

(42,'小二王'

,'2018-03-02 15:09:37'

,'女'

,'北京金燕龍'),

(43,'小二王'

,'2018-03-04 11:34:34'

,'女'

,'北京金燕龍'),

(45,'傳智播客'

,'2018-03-04 12:04:06'

,'男'

,'北京金燕龍'),

(46,'老王'

,'2018-03-07 17:37:26'

,'男'

,'北京'),

(48,'小馬寶莉'

,'2018-03-08 11:44:00'

,'女'

,'北京修正');

drop table if exists `account`;

create table `account` (

`id` int(11

) not null comment '編號'

, `uid` int(11

) default null comment '使用者編號'

, `money` double default null comment '金額'

, primary key (`id`)

, key `fk_reference_8` (`uid`)

, constraint `fk_reference_8` foreign key (`uid`) references `user` (`id`)

) engine=innodb default charset=utf8;

insert into `account`(`id`,`uid`,`money`) values (1,

46,1000),

(2,45

,1000),

(3,46

,2000);

drop table if exists `role`;

create table `role` (

`id` int(11

) not null comment '編號'

, `role_name` varchar(30

) default null comment '角色名稱'

, `role_desc` varchar(60

) default null comment '角色描述'

, primary key (`id`)

) engine=innodb default charset=utf8;

insert into `role`(`id`,`role_name`,`role_desc`) values (1,

'院長'

,'管理整個學院'),

(2,'總裁'

,'管理整個公司'),

(3,'校長'

,'管理整個學校');

drop table if exists `user_role`;

create table `user_role` (

`uid` int(11

) not null comment '使用者編號'

, `rid` int(11

) not null comment '角色編號'

, primary key (`uid`,`rid`)

, key `fk_reference_10` (`rid`)

, constraint `fk_reference_10` foreign key (`rid`) references `role` (`id`)

, constraint `fk_reference_9` foreign key (`uid`) references `user` (`id`)

) engine=innodb default charset=utf8;

insert into `user_role`(`uid`,`rid`) values (41,

1),(

45,1)

,(41,2);

該處使用的url網路請求的資料。

mybatis 多對多查詢

查詢使用者及使用者購買商品資訊。查詢主表是 使用者表 user 關聯表 由於使用者和商品沒有直接關聯,通過訂單和訂單明細進行關聯,所以關聯表是 orders orderdetail items select orders.order表的唯一標識 user表的唯一標識 user.username,us...

Mybatis結果對映 多對多

實際專案開發中,多對多關係也是非常常見的關係,比如,乙個購物系統中,乙個使用者可以有多個訂單,這是一對多的關係 乙個訂單中可以購買多種商品,一種商品也可以屬於多個不冋的訂單,訂單和商品就是多對多的關係。對於資料庫中多對多關係建議使用乙個中間衰來俊護關係,中間表中的訂單id作為外來鍵參照訂單表的id,...

mybatis多對多的問題彙總

結果顯示 檢視 發現沒有問題,難道是實體類的原因?後來發現實體類少了重寫tostring 方法 override public string tostring 但是還是有問題,如下,名字重複 原因在於user表和role表有欄位名重複 原來的sql語句 select u.r.from user u ...