我有两个表,第一个表是“ registration”表,第二个表是“ messages”表,注册表具有一列“ reg_id(主键)”和“ membership(“参与者”或消息表中有“ message_id(主键)”,“ reg_id(第一个表中的外键)”,“ receiver_reg_id”,“已完成(其值为0、1或2)”。
如何做到这一点,以便获得所有用户的列表,其中Membership ='graphics'和reg_id(来自注册表)= receiver_reg_id并count(completed = 0或completed = 1”“注意:不包括2“)<5。
这是我尝试过的方法,但是不起作用(我的查询):
SELECT r.reg_id
from registration r
join messages m
on (r.reg_id=m.receiver_reg_id)
WHERE r.membership='graphics' and sum(m.completed=1 or m.completed=0)<5
(但是它不起作用。)
样本数据:
注册表:
reg_id: 1, name: Mr A, membership: graphics.
reg_id: 2, name: Mr B, membership: participant.
reg_id: 3, name: Mr C, membership: graphics.
消息表:
message_id: 1, reg_id: 2, receiver_reg_id: 1, completed: 0.
message_id: 2, reg_id: 2, receiver_reg_id: 3, completed: 2.
message_id: 3, reg_id: 1, receiver_reg_id: 2, completed: 1.
message_id: 4, reg_id: 2, receiver_reg_id: 3, completed: 0.
message_id: 5, reg_id: 1, receiver_reg_id: 3, completed: 1.
message_id: 6, reg_id: 2, receiver_reg_id: 3, completed: 0.
message_id: 7, reg_id: 1, receiver_reg_id: 3, completed: 1.
message_id: 8, reg_id: 2, receiver_reg_id: 3, completed: 0.
message_id: 9, reg_id: 1, receiver_reg_id: 3, completed: 1.
预期输出:
reg_id :1.
只有reg_id:1满足整个条件。
消息表是一个会话,消息表上的reg_id是发送方的reg_id,而接收器_reg_id是接收方的reg_id。
它显示接收者具有图形成员资格,并且所有“完成的”(为1或0,但不是两个)(对于该特定接收者)的总和/计数小于5。
reg_id:2
失败,因为其成员身份不是图形
reg_id:3
失败,因为所有已完成的总和(总数为1或0)最多为5。
我希望这个问题更清楚。
答案 0 :(得分:0)
如果要对计算进行条件处理,则需要预先选择并在HAVING中进行引用。
SELECT r.reg_id,
sum(m.completed) as c
from registration r join
messages m on
r.reg_id=m.receiver_reg_id
WHERE r.membership='graphics'
and (m.completed=1
or m.completed=0) GROUP BY r.reg_id
HAVING c<5
答案 1 :(得分:0)
您不希望SUM
的行count
的{{1}}列的值为1
或0
。应该这样做:
completed
http://sqlfiddle.com/#!9/c515f0d/6
SELECT r.reg_id, count(completed) as da_count
from registration r
join messages m
on r.reg_id=m.receiver_reg_id
WHERE r.membership='graphics' and m.completed in (0, 1)
group by m.receiver_reg_id
having da_count < 5
添加该列的实际值,这样您的SUM
便不算什么。