我需要編寫一個查詢,將符合下列條件:如何編寫SQL查詢以從多個表中獲取信息?
考慮(6,8,10)的UID的列表,獲取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第一次嘗試,我已經糊塗自己努力使其發揮作用。任何幫助表示讚賞。
檢查你加入條件'users.uid = permissions.rid',你期望這樣做會怎樣? –
不,我進一步查看後,權限表沒有使用uid作爲外鍵。 –
哪種RDBMS適用於? * SQL *是一個標準 - 但供應商經常以不同的方式實現它,所以請添加一個標籤來指定您是使用'mysql','postgresql','sql-server','oracle'還是'db2' - 其他完全。 –