使用左外连接和on子句从具有公共列的两个不同表中检索数据

时间:2016-05-03 04:10:22

标签: mysql left-join

伙计我有两张不同的桌子。

表1:

contract-id | contract-date
  1         | 01-05-2016
  1         | 01-06-2016
  1         | 01-07-2016
  2         | 01-01-2016
  2         | 01-02-2016
  3         | 01-05-2016
  3         | 01-06-2016

表2:

invoice-number|contract-id|invoice-from-date|invoice-to-date
 1            |1          |01-05-2016       |31-05-2016
 2            |1          |15-05-2016       |31-05-2016
 3            |1          |25-05-2016       |31-05-2016

我的要求是,我必须显示当前月份来自表1的所有合同,我必须显示从表-2中为这些合同提出的发票数。如果有任何发票,它应显示其计数或只是零。预期的答案是:

contract-id|counts
 1         |3
 3         |0

合同ID:1的计数是3,因为我已经为当月提出了三张发票,而且合约ID:3的计数是0,因为我没有为它提出任何发票。而且合约ID:2缺失,因为它不属于当月。

这是我尝试过的:

    select cbm_contract_period_value_split.contract_id,
count(cbm_contract_invoice_request.contract_id),
cbm_contract_period_value_split.contract_date
from cbm_contract_period_value_split
left outer join cbm_contract_invoice_request
on cbm_contract_period_value_split.contract_id = cbm_contract_invoice_request.contract_id
and MONTH(cbm_contract_period_value_split.contract_date) = MONTH(CURDATE())
and MONTH(cbm_contract_invoice_request.invoice_for_the_period_of_from_date) = MONTH(CURDATE())

我已经发布了这个问题,但是现在我发布了一个带有我得到的答案的编辑版本。然而,我没有得到理想的答案。怎么了,我该怎么办?

3 个答案:

答案 0 :(得分:0)

试试这个。我认为你需要一个GROUP BY而我放入WHERE来过滤掉当前月份的行。

select pvs.contract_id,
       count(ir.contract_id) as counts,
       pvs.contract_date
from cbm_contract_period_value_split as pvs
left join cbm_contract_invoice_request as ir
on pvs.contract_id = ir.contract_id
and MONTH(ir.invoice_for_the_period_of_from_date) = MONTH(CURDATE())
WHERE MONTH(pvs.contract_date) = MONTH(CURDATE())
GROUP BY pvs.contract_id,pvs.contract_date

http://sqlfiddle.com/#!9/e5f08c/9

结果

contract_id     counts  contract_date
1               3       May, 01 2016 00:00:00
3               0       May, 01 2016 00:00:00

答案 1 :(得分:0)

SELECT Table-1.contract_id, Table-1.contract-date, COUNT(*) AS count FROM Table-2 LEFT JOIN Table-1 ON Table-1.contract_id =  Table-2.contract_id WHERE MONTH(Table-1.contract-date) = MONTH(CURDATE()) GROUP BY Table-1.contract_id

答案 2 :(得分:0)

尝试此查询..

{{1}}

<强> FIDDLE