【问题标题】:MySql Statement to Select Based On a Column in Intermediate TableMySql 语句基于中间表中的列进行选择
【发布时间】:2013-03-21 13:56:24
【问题描述】:

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

员工表

  • 用户 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(指向员工userID的外键)
  • 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 语句会得到一个涉及到的员工的列表。jurisdiction = "Texas";

【问题讨论】:

    标签: mysql sql select join


    【解决方案1】:
    SELECT 
     e.*
    FROM 
     jurisdictions j, user_jurisdiction uj, employees e
    WHERE
     uj.jurID = j.jurID AND 
     uj.userID = e.userID AND
     j.jurisdiction = 'Texas';
    

    【讨论】:

    • 是显式连接,相当于INNER JOIN语法
    【解决方案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        ║
    ╚════════╩═══════════╩══════════╩═══════╩══════════════╝
    

    如需进一步了解联接,请访问以下链接:

    【讨论】:

    • 谢谢。 “employees a”和“employees AS a”一样吗?
    • @dhee 是的。 AS 关键字是可选的
    • 即使我没有使用/不需要主键,我的中间表是否会受益于主键?
    • 不,jurisdictions.jurisdiction。这是一个例子,ALTER TABLE jurisdictions ADD INDEX (jurisdiction)
    • 我认为这比使用 SQL-86 standard 更好(就像其他答案所证明的那样),因为如果您忘记在where 子句。
    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多