如何编写SQL查询以从多个表中获取信息?

时间:2016-06-21 22:14:32

标签: mysql sql

我需要编写一个满足以下条件的查询:

给定一个uid列表(6,8,10),获取具有权限'管理用户'的用户的name_first和name_last。

CREATE TABLE users (
uid INT(11) AUTO_INCREMENT,
status TINYINT(3) NOT NULL DEFAULT 1,
name_first VARCHAR(256) DEFAULT '',
name_last VARCHAR(256) DEFAULT '',
email VARCHAR(256) DEFAULT '',
PRIMARY KEY (`uid`)
);

CREATE TABLE role(
rid INT(11) AUTO_INCREMENT,
name VARCHAR(256),
PRIMARY KEY `rid` (`rid`)
);

CREATE TABLE users_roles (
uid INT(11),
rid INT(11),
PRIMARY KEY (`uid`),
KEY `rid` (`rid`)
);

CREATE TABLE permissions (
rid INT(11),
permission VARCHAR(64),
UNIQUE KEY (`rid`, `permission`)
);

INSERT INTO users (uid, status, name_first, name_last, email) 
VALUES 
(1, 1, 'Joe', 'Montana', ''),
(2, 1, 'Eli', 'Manning', ''), 
(3, 1, 'Peyton', 'Manning', ''), 
(4, 1, 'Steve', 'Young', ''), 
(5, 1, 'John', 'Elway', ''), 
(6, 1, 'Robert', 'Griffin', ''), 
(7, 1, 'Joe', 'Montana', ''),
(8, 1, 'Tom', 'Brady', ''),
(9, 1, 'Drew', 'Brees', ''),
(10, 1, 'Andrew', 'Luck', '');

INSERT INTO role (rid, name) 
VALUES
(1, 'Teacher'),
(2, 'Athletic Directory'),
(3, 'Administrator');

INSERT INTO permissions (rid, permission) VALUES
(1, 'Administer users'),
(1, 'Administer courses'),
(1, 'Build Unicorns'),
(2, 'Administer groups'),
(3, 'Administer users'),
(3, 'Administer school');

INSERT INTO users_roles (uid, rid) VALUES
(1, 3),
(2, 1),
(3, 3),
(4, 1),
(5, 1),
(6, 2),
(7, 2),
(8, 3),
(10, 1);

这是我到目前为止所做的:

SELECT name_first, name_last FROM users
JOIN users_roles
ON users.uid = users_roles.uid
JOIN role
ON role.rid = users_roles.rid
JOIN permissions
ON users.uid = permissions.rid
WHERE users.uid = 8 AND permissions.permission = 'Administer users';

这是我编写SQL的第一次尝试,而且我在尝试使其工作时感到困惑。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

let image = UIImage(named: "my_image")
let transparentImage = image?.image(alpha: 0.5)

应该是

ON users.uid = permissions.rid

因为如果要查看NULL值,并非所有记录都与其他表相关,则需要使用LEFT JOIN(OUTER JOIN)而不是INNER JOIN。

此外,如果要查看所有记录,或者它与INNER JOIN相同,则应将permission ='admin ...'移至on条件。

ON role.rid = permissions.rid

答案 1 :(得分:0)

我添加了一个额外的列,以防万一你需要它。我创建了临时表进行测试,所以只需从查询中删除哈希标记:

SELECT
     U.name_first
    ,U.name_last
    ,P.permission PermissionName
    ,R.name RoleName
FROM
    #users U
    JOIN #users_roles UR
        ON  U.uid= UR.uid
    LEFT JOIN #role R
        ON  UR.rid = R.rid
    LEFT JOIN #permissions P
        ON  UR.rid = P.rid
WHERE
    U.uid IN (6,8,10)
    AND P.permission = 'Administer users'
;

答案 2 :(得分:0)

试试这个,但是你不会得到uid(6),因为它没有"管理用户"的许可。

从uid所在的用户中选择name_first,name_last (从那里的users_roles中选择uid (选择摆脱权限='管理用户'))和uid in(6,8,10);