1

表说明:

Table Members:
  id
  name
  status

Table Memberships:
  id
  date_start
  date_end
  date_added
  cost
  member_id
  status
  membership_type

Table Things:
  id
  name
  quantity
  member_id
  status

通过以下查询,我想获得表/视图,该表/视图将为每个“MEMBER”显示“MEMBERSHIP”,每个“MEMBER”的最后一列中都有“THINGS”的总和。

逻辑是这样的:“MEMBERS”是每条记录一个成员,每个“MEMBER”可以有多个“MEMBERSHIPS”,每个“MEMBER”可以有多个“THINGS”记录。

但是,以下查询返回我的事物数量乘以每个用户拥有的会员数量的总和。

  select
  memberships.id,
  memberships.member_id,
  members.name,
  members.status,
  memberships.membership_type,
  memberships.date_start,
  memberships.date_end,
  memberships.date_added,
  memberships.cost,
  memberships.status
  sum(things.quantity) as quantity
  from memberships
  right join members on memberships.member_id = members.id
  right join things on things.member_id = members.id
  where NOW() between memberships.date_start and memberships.date_end
  and memberships.status = 1
  and things.status = 1
  and members.status = 1
  group by members.id, memberships.member_id
4

2 回答 2

0

您需要在单独的子查询中计算每条记录,以便获得正确的结果。如果你加入表格并直接计算它,你将得到无效的结果,因为表格上members可以有多个记录,也可以有多个记录。membershipthingsThings

SELECT  a.*,
        COALESCE(b.totalMembership, 0) totalMembership,
        COALESCE(c.TotalThings, 0) TotalThings
FROM    Members a
        LEFT JOIN
        (
            SELECT  member_id, COUNT(*) totalMembership
            FROM    Memberships 
            GROUP   BY member_ID
        ) b ON a.ID = b.member_ID
        LEFT JOIN 
        (
            SELECT  member_ID, SUM(quantity) TotalThings
            FROM    Things
            GROUP   BY member_ID
        ) c ON a.ID = c.member_ID
于 2013-03-18T08:20:50.120 回答
0

当我在试验时,我发现了另一种不需要子查询的解决方法,它对于类似的场景 100% 有用。

我刚刚在 select 中添加了一个列,它的计算方式如下:

(sum(things.quantity) DIV count(distinct memberships.id)) as quantity

而且,瞧,它有效:)

于 2013-03-18T09:07:17.237 回答