【问题标题】:Join tables by child table id without inner select通过子表 id 连接表,无需内部选择
【发布时间】:2015-01-03 23:24:59
【问题描述】:

我有两个表(所有者和雇员)和一个映射表(所有者_雇员)

我需要一个 select 语句,它通过 employee_id 获取所有所有者员工,而不使用内部选择

例子:

SELECT * FROM employee e
[...Joins here...]
WHERE e.id = 1

应该返回

owner | employee
1     |   1
1     |   2

所有者表

id | title
----------
1  |  a
2  |  b
3  |  c

员工表

id | title
----------
1  |  a
2  |  a
3  |  b
4  |  c

Owner_Employee

id_owner | id_employee
----------------------
1        |    1
1        |    2
2        |    3
3        |    4

内部选择的工作实现在这里(可能工作,因为我从原始示例重写了它)

SELECT *
 FROM owner_employee oe
 JOIN owner o  ON o.id = oe.id_owner                                                 
 JOIN employee e ON e.id = oe.id_employee
 WHERE o.id in 
 (SELECT id_owner 
  FROM owner_employee oe
  WHERE oe.id_employee in (1))

【问题讨论】:

  • 您的预期结果与条件WHERE e.id = 1 冲突。这是不可能的,除非你错误地陈述了其中一个。
  • 请检查 querty (SELECT id 看起来不对,应该给出错误消息。因为有两个带有id 列的表,但owner_employee
  • without using inner selects你刚刚失去了我。
  • 怀疑他的意思是子选择
  • 表中的行是什么意思,什么是“所有者雇员”?不知何故,所有者1是员工1,也是员工2? “员工 ID 的所有所有者员工”与 SELECT id_employee FROM owner_employee 有何不同?您自己的查询不会返回。

标签: sql postgresql left-join inner-join outer-join


【解决方案1】:

大概是这样的:

 SELECT DISTINCT oe.*,o.*,e.*
 FROM owner_employee AS z 
 JOIN owner_employee oe on oe.id_owner = z.id_owner
 JOIN owner o  ON o.id = oe.id_owner
 JOIN employee e ON e.id = oe.id_employee
 WHERE z.id_employee in (1);

【讨论】:

    【解决方案2】:

    您提供的查询代码(不返回您的文本要求的内容)与

    相同
    SELECT *
    FROM owner_employee oe
    JOIN owner o  ON o.id = oe.id_owner                                                 
    JOIN employee e ON e.id = oe.id_employee
    WHERE oe.id_employee = 1
    

    但是您的文字要求“按employee_id 列出的所有所有者员工”显然没有意义。因为根据您的数据,一个所有者可以拥有多个 id_employee。

    如果你想要“所有 id_owners 和他们的 id_employees”:

    SELECT * FROM owner_employee
    

    如果您想要“所有所有者的 id_employees”:

    SELECT id_employee FROM owner_employee
    

    或者您可能想要“所有所有者,每个人都有一个员工 ID”?

    【讨论】:

      猜你喜欢
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多