SQL JOIN 从左边获取数据 table 仅当所有右边的列都匹配时

SQL JOIN get data from left table Only even if all right column match

我正在使用 PostgreSQL 9.5。我有 tables

EmployeeReportMarch
EmployeeId      Bonus      Day
---------------------------------
1               10000      23

EmployeeReport20152016
EmployeeId      Bonus      Month
---------------------------------
1               10000      02
1               10000      03

EmployeeReport
EmployeeId      Bonus      FiscalYear
---------------------------------
1               100000      20152016
1               90000       20162017

Calendar
Day_Id          Day    Month     FiscalYear
--------------------------------------------
2015-03-21      21     3         20152016
2015-03-22      22     3         20152016
2015-03-23      23     3         20152016
2015-03-24      24     3         20152016
2015-03-25      25     3         20152016

日历 table 从“2010-01-01”到“2016-12-31”。 财政年度是从 4 月 1 日到 3 月 31 日。

当我加入两个 table 以从

获取数据时
SELECT e.EmployeeeId, e.Bonus
FROM Employee e INNER JOIN Calendar c ON e.Day = c.Day
WHERE c.Day_Id BETWEEN '2015-02-01'::Date AND '2015-03-31'::Date;

输出:

EmployeeId     Bonus     Day_Id
-------------------------------------
1              10000     2015-02-23
1              10000     2015-03-23

SELECT e.EmployeeeId, e.Bonus
FROM Employee e INNER JOIN Calendar c ON e.Month = c.Month
WHERE c.Day_Id BETWEEN '2015-02-01'::Date AND '2015-03-31'::Date;

输出:

EmployeeId     Bonus
--------------------
1              100000
1              100000

--59 Rows (2 Month rows)

SELECT e.EmployeeeId, e.Bonus
FROM Employee e INNER JOIN Calendar c ON e.FiscalYear = c.FiscalYear
WHERE c.Day_Id BETWEEN '2015-02-01'::Date AND '2015-03-31'::Date;

输出:

EmployeeId     Bonus
--------------------
1              10000
1              10000

--365 Rows

但是table只剩下一条记录了。我也尝试过使用 OUTER JOIN,但结果是一样的,不知道怎么做。

join 合并来自两个 table 的匹配行。由于 employee table 中的日期与 calendar table 中的日期在 between 语句中给定的范围内匹配两次,这就是输出两行的原因。我想如果你使用任何连接,它会在输出中给出两行。

是架构问题,不是JOIN语句...

您的 table 日历有主键列 Day_Id,但您试图按日列加入它,这不是唯一的。有很多 Day = 23 的记录(确切地说,每年 12 个)。因此,您每个月在 table.

中获得 1 行

要解决此问题,您应该按 Day_Id 列加入(或一次按 3 列:年 + 月 + 日)。