通过匹配多个列从多个表中选择数据

时间:2012-12-11 10:08:50

标签: mysql sql

我有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?

3 个答案:

答案 0 :(得分:1)

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

  SELECT UserID, UserName, Level, Department, Position FROM User   
INNER JOIN Employee ON UserId=EmployeeID INNER JOIN Authorization ON UserId = AuhtorizationId 

答案 1 :(得分: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

答案 2 :(得分:0)

查询:

<强> SQLFiddleExample

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 |