一個用戶具有多個角色,請查詢出改表中具有該用戶的所有角色的其他用戶


DROP TABLE IF EXISTS `emp`;

CREATE TABLE `emp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`number` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`role` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;

 

INSERT INTO `emp` VALUES (1,1001,'a','read');
INSERT INTO `emp` VALUES (2,1001,'a','write');
INSERT INTO `emp` VALUES (3,1001,'a','copy');
INSERT INTO `emp` VALUES (4,1002,'b','read');
INSERT INTO `emp` VALUES (5,1002,'b','write');
INSERT INTO `emp` VALUES (7,1003,'c','listen');
INSERT INTO `emp` VALUES (8,1003,'c','read');
INSERT INTO `emp` VALUES (9,1004,'d','read');
INSERT INTO `emp` VALUES (10,1004,'d','write');
INSERT INTO `emp` VALUES (11,1005,'e','read');
INSERT INTO `emp` VALUES (12,1005,'e','write');

有兩種方式可以查詢(Mysql)

1.select ep.number,ep.role from emp ep,

(select role,number from emp where number=1002) e

where e.role= ep.role and e.number!= ep.number

group by number

having count(*)=(select count(number) from emp where number=1002 );

在這里having 后的 要寫count(*) 而不是count(number) 否則會報錯

 

結果:

number count(*)

1001         2
1004     2
1005     2

2.select number,count(*) from emp

where role in (select role from emp where number=1002)

and number !=1002

group by number

having count(number) =(select count(number) from emp where number=1002);

number count(*)

1001         2
1004     2
1005     2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM