我正在使用MariaDB 10.3,并且具有如下表:
post_id post_content post_user_id post_shared
1 Test1 1 0
2 Test2 2 0
3 Test2 1 2
post_shared = 0表示这是原始帖子,不共享。
我正在寻找一种方法,以了解该帖子是否已由特定用户共享(来自post_user_id)。输出示例如下:
post_id isShared ( post_user_id 1)
1 0 (false)
2 1 (true)
3 0 (false)
我在同一张表上尝试了LEFT JOIN并使用if条件进行了检查,但是代码向我返回了错误的值。
向所有人寻求帮助:)
答案 0 :(得分:1)
您可以使用相关子查询或left join
添加布尔标志。如果没有重复项:
select t.*, (ts.post_id is not null) as isShared
from t left join
ts
on ts.post_shared = t.post_id and
ts.post_user_id = 1;
作为相关子查询,它看起来像:
select t.*,
(exists (select 1
from ts
where ts.post_shared = t.post_id and
ts.post_user_id = 1
)
) as isShared
答案 1 :(得分:0)
使用corealted子查询
CKQueryOperation.maximumResults
答案 2 :(得分:0)
存在:
select
t.post_id,
case when exists (
select 1 from tablename
where post_id <> t.post_id
and post_shared = t.post_id
) then 1
else 0
end isShared
from tablename t
答案 3 :(得分:0)
使用左联接
SELECT t1.post_id, IF(t2.post_id IS NULL, FALSE, TRUE)
FROM Test as t1
LEFT JOIN Test as t2 ON (t1.post_id = t2.post_shared and t2.post_user_id = 1)
order by t1.post_id;
答案 4 :(得分:0)
使用案例和基于文本的Output的解决方案:
SELECT *,
CASE
WHEN post_shared > 0 THEN 'This story has been shared'
ELSE 'This story has not been shared'
END AS share_status
FROM Test