PostgreSQL连接子查询不能限制查询

时间:2016-05-07 18:24:40

标签: sql postgresql join subquery

向DBA STACKEXCHANGE提出这个问题: https://dba.stackexchange.com/questions/137878/postgresql-join-subquery-cant-restrict-query

我正在开展一项分拆项目,该项目会分割出一项活动欠款。用户可以是多个组的一部分,每个组都有自己的运行余额。

我正在尝试运行一个查询,该查询将返回个人用户所欠的金额'所有群体。

目前查询如下:

SELECT 
    SUM(owe) 
FROM (
    SELECT 
        (expenses.amount/count(*))
    AS owe 
    FROM expenses 
    LEFT JOIN user_expenses 
    ON (
        expenses.id = user_expenses.expense_id
        ) 
    WHERE expenses.paid_by != 1 
    GROUP BY expenses.id
    ) 
AS total;

问题是此查询全面检索所有费用。我想做的是限制使用:

WHERE user_expenses.user_id = 1

如何将其添加到上述查询(在子查询中)以将结果限制为仅与该用户关联的费用?

TABLE SCHEMA(如果这可能有帮助):

USERS
id
name
username
email

EXPENSES
id
created_at
updated_at
title
amount
group_id
paid_by
img_url
note

USER_EXPENSES (join table)
id
expense_id
user_id

GROUPS
id
created_at
name
desc

USER_GROUPS
id
user_id
group_id

更多样本信息以便澄清: 如果我运行此查询 -

SELECT 
    e.title,
    e.amount,
    (e.amount/count(*)) AS owe, count(*) AS members 
      FROM expenses e LEFT JOIN
           user_expenses ue
           ON e.id = ue.expense_id
      WHERE e.paid_by != 1 
      GROUP BY e.id;

我得到这样的东西(带有虚拟数据): enter image description here

如果我运行以下内容:

SELECT 
    e.title,
    e.amount,
    (e.amount/count(*)) AS owe, count(*) AS members 
      FROM expenses e LEFT JOIN
           user_expenses ue
           ON e.id = ue.expense_id AND ue.user_id = 1
      WHERE e.paid_by != 1 
      GROUP BY e.id;

我明白了(注意成员数): enter image description here

2 个答案:

答案 0 :(得分:0)

如果您的查询有效,那么您只需将其添加到子查询中:

SELECT SUM(owe) 
FROM (SELECT (e.amount/count(*)) AS owe 
      FROM expenses e LEFT JOIN
           user_expenses ue
           ON e.id = ue.expense_id AND ue.user_id = 1
      WHERE expenses.paid_by <> 1 
      GROUP BY expenses.id
     ) t;

答案 1 :(得分:0)

我们最终得到了两个解决方案。非常感谢一位出色的团队成员,他们通过它提供了一些有用的东西,并且可以认为它更便宜。感谢两者。

原来HAVING是获得理想解决方案的关键部分(感谢@ andriy-m):

  

HAVING子句已添加到SQL,因为WHERE关键字无法与聚合函数一起使用

SELECT SUM(owe) 
FROM (
  SELECT 
    (e.amount/count(*)) AS owe 
  FROM expenses e 
  LEFT JOIN
       user_expenses ue
  ON e.id = ue.expense_id
  WHERE e.paid_by != 1 
  GROUP BY e.id
  HAVING COUNT(ue.user_id = 1 OR NULL) > 0
) 
AS total;

另外,为了纪念在此努力工作的PJ:

SELECT SUM(owe) 
FROM (SELECT (expenses.amount/count(*)) AS owe 
FROM expenses 
LEFT JOIN user_expenses ON (expenses.id = user_expenses.expense_id) 
WHERE expenses.paid_by != 1 
AND expense_id IN (select expense_id from users LEFT JOIN user_expenses 
ON (1 = user_expenses.user_id)) GROUP BY expenses.id)
AS total;