表说明:
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