0

我正在使用 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 条件进行检查,但代码返回了错误的值。

谢谢大家的帮助:)

4

5 回答 5

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
于 2019-07-07T11:14:01.877 回答
0

使用核心子查询

select t1.* from table_name t1
where exists( select 1 from table_name t2 where t1.post_user_id=t2.post_user_id
                          and post_shared<>0)
于 2019-07-07T11:09:07.233 回答
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
于 2019-07-07T11:14:08.863 回答
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;
于 2019-07-07T11:29:23.570 回答
0

使用案例和基于文本的输出的解决方案:

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
于 2019-07-07T11:36:32.867 回答