如何检查同一 table 中的其他列是否使用了 id
How chceck is id is used in other column in same table
我使用的是 MariaDB 10.3,我 table 喜欢:
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,未共享。
我正在寻找一种方法来了解 post 是否已被特定用户(来自 post_user_id)共享。示例输出如下:
post_id isShared ( post_user_id 1)
1 0 (false)
2 1 (true)
3 0 (false)
我尝试对同一个 table 进行 LEFT JOIN 并使用 if 条件进行检查,但代码返回错误值。
谢谢大家的帮助:)
使用相关子查询
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)
您可以使用相关子查询或 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
存在:
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
使用左连接
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;
解决方案使用案例和 text-based 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
我使用的是 MariaDB 10.3,我 table 喜欢:
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,未共享。
我正在寻找一种方法来了解 post 是否已被特定用户(来自 post_user_id)共享。示例输出如下:
post_id isShared ( post_user_id 1)
1 0 (false)
2 1 (true)
3 0 (false)
我尝试对同一个 table 进行 LEFT JOIN 并使用 if 条件进行检查,但代码返回错误值。
谢谢大家的帮助:)
使用相关子查询
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)
您可以使用相关子查询或 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
存在:
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
使用左连接
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;
解决方案使用案例和 text-based 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