3

在数据库中,我有一个用户名表和一个权限表。我还有一个中间表,可以将用户分配到一个或多个司法管辖区。

员工表

  • 用户 ID(主键)

记录:

+--------+-----------+----------+
| userID | firstName | lastName |
+--------+-----------+----------+
|      6 | John      | Doe      |
|     11 | lisa      | lopez    | 
+--------+-----------+----------+

管辖表

  • jurId(主键)
  • 地区

记录:

+-------+--------------+
| jurID | jurisdiction |
+-------+--------------+
|     1 | California   |
|     2 | Texas        |
|     3 | Washington   |
|     4 | South Dakota |
|     5 | Alaska       |
|     6 | Ohio         |
+-------+--------------+

user_jurisdiction

  • userID(指向员工用户ID的外键)
  • jurID(指向司法管辖区 jurID 的外键)

记录:

    +--------+-------+
    | userID | jurID |
    +--------+-------+
    |      6 |     2 |
    |      6 |     3 |
    |     11 |     2 |
    +--------+-------+

我已经尝试了几个小时来提出一个 sql 语句,该语句将选择/列出来自“Texas”的所有工作人员。我一直在使用这个 sql 语句的许多争执,但没有成功:

SELECT  jurisdictions.jurisdiction,
        employees.firstName
FROM    jurisdictions,
        employees
        INNER JOIN user_jurisdictions
            ON  user_jurisdictions.jurID = jurisdictions.jurID AND 
                user_jurisdictions.userID = employees.userID
WHERE   jurisdictions.jurisdiction = "Texas";

但我没有成功。什么 sql 语句会得到一个从jurisdictions.jurisdiction = "Texas"; 中涉及的员工列表。

4

2 回答 2

2

您现在正在做的是您正在从表中生产 Catersian 产品:employeesjurisdictions. 连接的正确语法是显式定义两个表之间的连接类型。

SELECT  a.*, c.*
FROM    employees a
        INNER JOIN user_jurisdiction b
            ON a.userID = b.userID
        INNER JOIN jurisdictions c
            ON b.jurID = c.jurID
WHERE   c.jurisdiction = 'Texas'

当前查询的输出

╔════════╦═══════════╦══════════╦═══════╦══════════════╗
║ USERID ║ FIRSTNAME ║ LASTNAME ║ JURID ║ JURISDICTION ║
╠════════╬═══════════╬══════════╬═══════╬══════════════╣
║      6 ║ John      ║ Doe      ║     2 ║ Texas        ║
║     11 ║ lisa      ║ lopez    ║     2 ║ Texas        ║
╚════════╩═══════════╩══════════╩═══════╩══════════════╝

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-03-31T07:39:42.290 回答
2
SELECT 
 e.*
FROM 
 jurisdictions j, user_jurisdiction uj, employees e
WHERE
 uj.jurID = j.jurID AND 
 uj.userID = e.userID AND
 j.jurisdiction = 'Texas';
于 2013-03-31T07:41:30.207 回答