0

抱歉,如果这是一个愚蠢的问题,但最近没有使用太多 SQL,也找不到太多帮助。

即使结果为 0 或 null,我也需要让所有行显示在结果中。我遇到的问题是由于 WHERE 子句(没有 WHERE,所有行都显示但数据不显示)。

SELECT SUM(c.amount) AS 'total_income', p.ref_id AS 'property'
FROM property p
LEFT JOIN contract c
ON p.id = c.property_ref_id
LEFT JOIN contract_payment cp
ON c.id = cp.contract_id   
WHERE cp.paid = 1 AND year(cp.date_paid) = :year
GROUP BY p.id

显示没有 Where 和 Bad Data 的结果集将是这样的

array
  0 => 
    array
      'total_income' => null
      'property' => string 'test/0001' (length=9)
  1 => 
    array
      'total_income' => null
      'property' => string 'test/0002' (length=9)
  2 => 
    array
      'total_income' => string '200' (length=3)
      'property' => string 'test/0003' (length=9)
  3 => 
    array
      'total_income' => string '16100' (length=5)
      'property' => string 'test/0004' (length=9)

虽然这是带有 WHERE 子句和良好数据但不是所有行的结果集

array
  0 => 
    array
      'total_income' => string '4200' (length=4)
      'property' => string 'test/0004' (length=9)

有人可以告诉我可以对 SQL 进行哪些修改以检索我想要的数据吗?

4

1 回答 1

0

问题是您要过滤掉cp表中所有不匹配的行,因为cp.paid当那里没有匹配时不能为 1。

将 WHERE 子句更改为:

WHERE cp.contract_id IS NULL OR (cp.paid = 1 AND year(cp.date_paid) = :year)

或者将该条件移动到 LEFT JOIN 的 ON 子句中,使用 cp:

ON c.id = cp.contract_id AND cp.paid = 1 AND year(cp.date_paid) = :year
于 2013-04-04T09:40:23.373 回答