3

这是我的情况。

PayTable
+-------+------+--------------+
| Craft | Job  | sequence     |
+-------+------+--------------+
| 400   | 1    | 1            |
+-------+------+--------------+
| 401   | 2    | 2            |
+-------+------+--------------+
| 5501  | 2    | 3            |
+-------+------+--------------+

Jobs
+-------+------+------+
| Job | CraftTemplate |
+-------+------+------+
| 1   | 1             |
+-------+------+------+
| 2   | 1             |
+-------+------+------+


Pay Template
+-------+--+
| Template |
+-------+--+
| 1        |
+-------+--+

PayCraftTemplate
+-------+------+---------+
| PayTemplate    | Craft |
+-------+------+---------+
| 1              | 400   |
+-------+------+---------+
| 1              | 401   |
+-------+------+---------+

我需要做的是从 PayTable 中找到 PayCraftTemplate 中不存在该工艺的所有工艺。作为一种反连接模式,这似乎非常简单,但我似乎无法让数据正确返回。

加入链接如下:

PayTable INNER JOIN Jobs by Job -> Job
Jobs LEFT OUTER JOIN Pay Template by CraftTemplate -> Template
Pay Template LEFT OUTER JOIN by Template -> PayTemplate 

这是我目前的尝试:

select
    *
FROM
    PayTable
WHERE NOT EXISTS (
    SELECT 1
        FROM
    Jobs 
        LEFT OUTER JOIN PayTemplate
        ON PayTemplate.Template = Jobs.CraftTemplate
    LEFT OUTER JOIN PayCraftTemplate 
        ON PayCraftTemplate.Template = PayTemplate.Template
    WHERE 
        PayTable.Craft = PayCraftTemplate.Craft AND PayTable.Job = Jobs.Job
) AND PayTable.Job IS NOT NULL AND PayTable.Craft IS NOT NULL

这没有返回我期望的数据,我希望 PayTable 的第 3 行只返回而不是我得到第 1,2 行

4

1 回答 1

1

我猜你移动了一些东西来发布问题并基本上修复了它。从上面的查询中,您只需更改PayCraftTemplate.TemplatePayCraftTemplate.PayTemplate

起初我认为这是left join一个where无意中将其变成 的问题inner join,但在这种情况下inner join无论如何都是需要的,所以这不是问题。

select    *
from  PayTable
where not exists (
  select 1
  from Jobs 
    inner join PayTemplate
      on PayTemplate.Template = Jobs.CraftTemplate
      and Jobs.Job = PayTable.Job
    inner join PayCraftTemplate 
      on PayCraftTemplate.PayTemplate = PayTemplate.Template
     and PayCraftTemplate.Craft  = PayTable.Craft 
  )
  and PayTable.Job is not null
  and PayTable.Craft is not null

结果:

+-------+-----+----------+
| Craft | Job | sequence |
+-------+-----+----------+
|  5501 |   2 |        3 |
+-------+-----+----------+
于 2017-02-17T14:00:58.463 回答