在where子句中过滤右连接数据
我有一个简单的表结构,其中每个项目行都有一个状态。我正在寻找的是查询每个状态并计算有多少项目使用该状态。可能并非所有状态都会被使用,因此我需要考虑空值和零计数。
我的表结构如下:
Table: Items
Id, State_id, Text, Status
Table: States
State_id, Name
这就是我所拥有的:
SELECT statealias1_.State_id as y0_,
count(this_.Id) as y1_
FROM Items this_
right join States statealias1_
on this_.State_id = statealias1_.State_id
WHERE (not (statealias1_.State_id in (5, 6, 7, 8))
or statealias1_.State_id is null)
and (this_.Status = 'InProgress'
or this_.Status is null)
GROUP BY statealias1_.State_id;
该查询在包含所有状态时有效(有 8 个状态,我不包括后半部分)。我不确定为什么这没有返回所有带有计数的状态,无论空值如何,因为我似乎包含空值。
I have a simple table structure where each item row has a status. What I'm looking is to query for each status and count how many items use that state. It's possible that not all statuses will be used so I need to account for nulls and zero counts.
My table structures is as follows:
Table: Items
Id, State_id, Text, Status
Table: States
State_id, Name
This is what I have:
SELECT statealias1_.State_id as y0_,
count(this_.Id) as y1_
FROM Items this_
right join States statealias1_
on this_.State_id = statealias1_.State_id
WHERE (not (statealias1_.State_id in (5, 6, 7, 8))
or statealias1_.State_id is null)
and (this_.Status = 'InProgress'
or this_.Status is null)
GROUP BY statealias1_.State_id;
This query works when all states included (there are 8 states and I'm excluding the second half). I'm not sure why this isn't returning me all states with count regardless of nulls as I appear to be including nulls.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会反转它......从您的“状态”条目开始,然后左连接到您想要包含的内容的预聚合结果集
I would reverse it... start with your "Status" entries and LEFT JOIN to a pre-aggregated result set of what you DO want to include
你已经很接近了,但是你的做法与我通常看到的方式相反。
You are close, but you have it backwards from how I usually see it done.
我认为你的SQL是正确的,但是你的where条件可能有逻辑错误。
您有:
您的意思是:
I think your SQL is correct, but you have a possible logic error in your where condition.
You have:
Did you mean: