基于中间表中的列选择的MySql语句

时间:2013-03-31 07:37:08

标签: mysql sql select join

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

员工表

  • userID(主键)
  • 的firstName
  • lastName的

记录:

+--------+-----------+----------+
| 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的Foriegn Key)
  • jurID(Foriegn Key指向司法管辖区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&#34 ;;

2 个答案:

答案 0 :(得分:2)

您现在正在做的是从桌子employeesjurisdictions制作caterian产品。正确的连接语法是显式定义两个表之间的连接类型。

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        ║
╚════════╩═══════════╩══════════╩═══════╩══════════════╝

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

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