You need to enable JavaScript to run this app. 多对多关系下按用户/所属组(优先用户)查询内容记录的SQL与表结构优化咨询
优惠活动
大模型
产品
解决方案
定价
更多

多对多关系下按用户/所属组(优先用户)查询内容记录的SQL与表结构优化咨询

数据库关联查询设计与性能优化问题

业务场景

目前设计了两张存储表:

  • post 内容主表:存储内容本身的基础数据
  • post_rel 关联关系表:关联内容与对应用户、所属用户组,同时可存储针对指定用户/组的自定义配置(如自定义标题、自定义封面等)

需要实现的查询规则为:给定用户ID为160、其所属用户组ID为7时,优先返回该用户自身关联的有效内容记录;若没有匹配到该用户的关联记录,再返回其所属用户组关联的有效内容记录。

现有表结构

post 内容主表示例

id  |  title  |  content    |   cover  | status
------------------------------------------------
1   | first   |  content 1  | /img/... |   1
2   | second  |  content 2  | /img/... |   1
3   | another |  content 3  | /img/... |   1
4   | four    |  content 4  | /img/... |   1
5   | five    |  content 5  | /img/... |   1

post_rel 关联关系表示例

id  | group_id | user_id | post_id |  title   |   cover  | sort | status
---------------------------------------------------------------------------
1   | 7        | NULL    | 1       | g title  | img/...  | 1    | 1
2   | NULL     | 160     | 1       | u title  | NULL     | 2    | 1     ***  selected for user_id
3   | 7        | NULL    | 2       | NULL     | img/...  | 6    | 0
4   | NULL     | 160     | 2       | NULL     | img/...  | 4    | 1     ***  selected for user_id
5   | NULL     | 160     | 3       | some     | img/...  | 3    | 1     ***  selected for user_id
6   | 7        | NULL    | 4       | NULL     | img/...  | 9    | 1     ***  selected for group_id
7   | NULL     | 165     | 5       | NULL     | img/...  | 5    | 0

当前使用的查询SQL

select 
    `post_rel`.`title` as `custom_title`, 
    `post_rel`.`cover` as `custom_cover`, 
    `post_rel`.`group_id`, 
    `post_rel`.`user_id`, 
    `post`.* 
from 
    `post` 
        inner join `post_rel` on `post`.`id` = `post_rel`.`post_id` 
        where 
            `post`.`status` = 1 
            and `post_rel`.`status` = 1 
            and ( 
                `post_rel`.`user_id` = 160 
                or ( 
                    `post_rel`.`group_id` = 7 
                    and `post_rel`.`post_id` not in (
                            select 
                                `post_rel`.`post_id` 
                            from 
                                `post_rel` 
                            where 
                                `post_rel`.`user_id` = 160
                    )
                )
            )
order by 
    `post_rel`.`sort` asc

待确认的核心问题

  • 当前的查询逻辑是否存在设计不合理的地方?
  • 语句中嵌入的NOT IN子查询,在表数据量较大的场景下,是否会出现明显的性能下降问题?
  • 是否可以编写逻辑更简洁、性能更优的等价SQL实现需求?
  • 现有两张表的结构是否存在可优化的空间?

内容的提问来源于stack exchange,提问作者Ali.Sh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.07 02:54:04