mysql子查询,如同条件(仅在需要时)

时间:2015-04-30 21:37:22

标签: mysql if-statement full-text-search case

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

Databasescheme:

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

1 个答案:

答案 0 :(得分:1)

好的,这可能不是最好的答案,但这解决了上述问题而不使用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不是。