0

我有 3 个这样的表:

表用户

    +---------+-----------------+
    | UserId  | UserName        |
    +---------+-----------------+
    | 1       | one@test.com    |
    | 2       | two@test.com    |    
    | 3       | three@test.com  |  
    | 4       | four@test.com   |
    +---------+-----------------+

表员工

    +-------------+----------------+------------+----------+---------+
    | EmployeeId  | Email          | Department | Position | Duty    |
    +-------------+----------------+------------+----------+---------+
    | 1           | one@test.com   | Accounting | Manager  | Aproval |
    | 2           | two@test.com   | Accounting | Manager  | NULL    |
    | 3           | three@test.com | Marketing  | Staff    | NULL    |
    | 4           | four@test.com  | Purchasing | Staff    | NULL    |
    +-------------+----------------+------------+----------+---------+

表授权

    +------------------+----------------+------------+----------+----------+
    | AuhtorizationId  | Level          | Department | Position | Duty     |
    +------------------+----------------+------------+----------+----------+
    | 1                | 1              | Accounting | Manager  | NULL     |
    | 2                | 2              | Marketing  | Staff    | NULL     |
    | 3                | 3              | Purchasing | Staff    | NULL     |
    | 4                | 4              | Accounting | Manager  | Approval |
    +------------------+----------------+------------+----------+----------+

如何构造一个 MySQL 查询来检索 UserId、UserName/Email、Level、Department 和 Position?

4

3 回答 3

1

如果我正确理解所有表格关系

  SELECT UserID, UserName, Level, Department, Position FROM User   
INNER JOIN Employee ON UserId=EmployeeID INNER JOIN Authorization ON UserId = AuhtorizationId 
于 2012-12-11T10:16:20.873 回答
0
SELECT User.UserID, User.UserName, Authorization.Level, Authorization.Department, Authorization.Position FROM User INNER JOIN Employee ON User.UserId=Employee.EmployeeID INNER JOIN Authorization ON Employee.Department = Authorization.Department WHERE Employee.Position=Authorization.Position AND Employee.Duty=Authorization.Duty
于 2012-12-11T10:21:13.247 回答
0

询问:

SQLFiddle示例

SELECT 
u.`UserID`, 
u.`UserName`, 
a.`Level`, 
e.`Department`, 
e.`Position` 
FROM `User` u   
  LEFT JOIN `Employee` e
    ON u.`UserId` = EmployeeID 
  LEFT JOIN `Authorization` a 
    ON u.`UserId` = a.`AuhtorizationId` 

结果:

| USERID |       USERNAME | LEVEL | DEPARTMENT | POSITION |
-----------------------------------------------------------
|      1 |   one@test.com |     1 | Accounting |  Manager |
|      2 |   two@test.com |     2 | Accounting |  Manager |
|      3 | three@test.com |     3 |  Marketing |    Staff |
|      4 |  four@test.com |     4 | Purchasing |    Staff |
于 2012-12-11T21:46:33.927 回答