MySQL 子查询就像条件一样(仅在需要时)



我想对包含属于组内主题的帖子的表执行文本搜索。根据这些组的隐私设置,我需要运行一个子查询来检查请求用户是否是包含搜索匹配的组的成员。

数据库方案:

Table: posts
Columns: id, group_id, title, text
Table: groups
Columns: group_id, privacy
Table: group_memberships
Columns: group_id, is_member

组表中的隐私列包含一个整数值。

1 = public, anyone can access the data    
2 = system, anyone can access the data
3 = private, only members can access the data

查询应执行的操作:

1. Find some matches in the post table
2. Check the group privacy in the groups table -> a value HIGHER THAN 2 requires a membership check
3. Do a membership check on the group_memberships table if required

我真的不知道如何处理这个问题。

看起来 mysql 支持两种方式?IF 语句和大小写表达式?

正确的方法是什么?

PS:成员资格检查的子查询应该是可选的,并且仅在需要时触发。

"像"这样的东西..伪代码:

SELECT p.id, p.title, p.text
FROM posts p
INNER JOIN groups g
ON g.group_id = p.group_id
AND p.title is not null
WHERE EXISTS(
CASE
WHEN g.privacy < 2 THEN ''everything is ok. Nothing more needed''
ELSE (''Membership check needed'')
END
)

编辑:有人可以确认这是正确的方法吗?

SELECT p.id, p.channel_id, p.title, g.name
FROM posts p
INNER JOIN user_groups g
ON g.id = p.channel_id
AND p.title is not null
WHERE g.privacy < 2 OR (SELECT count(*) FROM user_groups_memberships WHERE uid = 1 AND channel_id = p.channel_id AND rank IS NOT NULL AND is_banned IS NULL) = 1
GROUP BY p.parent_id

好吧,这可能不是最好的答案,但这可以在不使用 IF 或 CASE 表达式的情况下解决上述问题。

select 
   p.id,
   p.group_id,
   p.title,
   p.text
from
   posts p,
   groups g
where 
   p.group_id = g.group_id 
   and
   ( 
     g.privacy<3 
     or 
     ( g.privacy => 3 and 
          (select is_member from group_memberships gm where gm.group_id = g.group_id) = 1)
   );

假设这里is_member = 1意味着id是成员,0意味着id不是。

最新更新