结构
成员 id(auto,int),fullName(varchar),isReseller(enum),reseller_id(int),country_id,city_id,town_id,landLine,admin(enum)
订阅 id(auto,int),transaction_id(int),magazine_id(int),cargo(varchar),startDate(date),endDate(date),active(enum),status(枚举),reseller_id(int),member_id(int)
交易 id(auto,int),bankaccount_id(int),member_id(int),creator_admin_id(int),paymentDate(date)
杂志 id(auto,int),name(varchar)
bankaccounts id(auto,int),name(varchar)
查询
SELECT
s.id, s.cargo, s.startDate, s.endDate, s.active, s.status,
mag.name as magazineName,
b.name as bankName, t.id as transaction_id,
m.fullName, m.id as member_id,
mm.fullName as resellerName, mm.id as reseller_id
FROM asw_subscriptions as s
INNER JOIN asw_members as m ON m.id = s.member_id
INNER JOIN asw_transactions as t ON t.id = s.transaction_id
INNER JOIN asw_members as mm ON mm.id = t.member_id
INNER JOIN asw_magazines as mag ON mag.id = s.magazine_id
INNER JOIN asw_bankaccounts as b ON b.id = t.bankaccount_id
WHERE
m.fullName LIKE '%john%' AND
m.country_id = '224' AND
m.admin = '0' AND
m.reseller_id = '45677' AND
s.magazine_id = '1' AND
s.active = '1' AND
s.reseller_id = '45677' AND
t.paymentDate BETWEEN '2011-10-01' AND '2011-10-29' AND
t.creator_admin_id = '45677' OR
t.member_id = '45677'
ORDER BY id DESC LIMIT 0, 25
问题
上面的此查询显示每个订阅订单都由转销商完成,无论会员和订阅状态的任何搜索条件如何(如果我搜索active = '1'
,它仍会显示所有订阅订单。)
即使我要写约翰,它也会显示所选经销商的所有订单。
就像我在查询经销商的订单时查询了指定的付款日期(t.paymentDate BETWEEN '2011-10-01' AND '2011-10-29'
)。
我不知道如何解释这种情况。如果我不清楚请告诉我,我会尝试编辑我的问题并更具体。
提前谢谢。
答案 0 :(得分:1)
我不清楚你想要回复什么数据,但我想也许你应该从交易中加入成员(只需一次),然后做一些分组来计算订单(如果这就是你想要的) 。 另请注意,在OR之前评估AND - 因此最终的OR语句与所有AND评估在一起。使用括号()正确分组OR / AND / BETWEEN语句。
答案 1 :(得分:1)
你内心的加入:
INNER JOIN asw_members as mm ON mm.id = t.member_id
已经保证t.member_id = mm.id所以在OR语句的where子句中添加完全相同的条件可以保证你只根据连接得到完整的集合。请参阅上面关于括号的答案。
如果mm是经销商且m是会员,我想您需要以下内容:
INNER JOIN asw_members as mm ON (mm.id = t.member_id OR t.member_id = mm.id)
然后在你的WHERE子句中:
m.reseller_id = mm.id AND
s.reseller_id = mm.id AND
mm.id = '45677' AND
....<other filters>
有时,如果您要两次加入一张桌子,您可能希望将您的转销商缩写为r,将您的成员缩写为m。它使人们更容易记住谁是谁。