我知道这张桌子,
元:
| id | comment_id | key | value |
| 1 | 1 | _status | pending |
| 2 | 2 | _comment_id | 1 |
| 3 | 2 | _status | pending |
我想要的是从_status = pending
的行中检索comment_id值,这些行没有指向自身的_comment_id =
行。
更好地解释一下这个伪代码。
status = getRows( {key: _status, value: pending} );
ids = getRows( {key: _comment_id } )
what_i_want = []
foreach status as comment_status_id:
if comment_status_id not in ids:
what_i_want[] = status_id
这样做的最佳方式是什么?是否可以仅使用sql执行此操作?
如果该表应该返回:[2]
答案 0 :(得分:1)
您可以使用group by
和having
:
select comment_id
from table t
group by comment_id
having sum(case when key = '_status' and value = 'pending' then 1 else 0
end) > 0 and
sum(case when key = '_comment_id' and value = cast(comment_id as varchar(255))
then 1 else 0
end) = 0;
如果您正在寻找status =“pending”,并且注释ID为和,则注释ID不会指向自身:
select comment_id
from table t
group by comment_id
having sum(case when key = '_status' and value = 'pending' then 1 else 0
end) > 0 and
sum(case when key = '_comment_id' then 1 else 0 end) > 0 and
sum(case when key = '_comment_id' and value = cast(comment_id as varchar(255))
then 1 else 0
end) = 0;