我按以下方式设置了一系列表格(为了便于阅读,它们已被简化):
user
- id
- name
user_has_oi_relationship
- user_id
- oi_relationship_id
oi_relationship
- id
- description
chat_group_has_oi_relationship
- chat_group_id
- oi_relationship_id
chat_group
- id
- name
- description
“user”表中的每个条目都附加了一系列 OI 关系,如“user_has_oi_relationship”表中所定义。每个聊天组还附加了一系列 OI 关系,如“chat_group_has_oi_relationship”表中所定义。
我想做的是根据他们的 OI 关系,根据他们的用户 ID 定义,为特定用户选择可用的聊天组。
我通常很擅长连接等,但这个让我很困惑。我一直让所有的组都返回!
最佳答案
好的,让我们从用户的 user_has_oi_relationship 开始:
--query 1
select oi_relationship_id from user_has_oi_relationship where user_id =:user_id
现在去有那个 oi 的 chat_groups
--query 2
select chat_group_id from chat_group_has_oi_relationship
where oi_relationship_id in (
--query 1
select oi_relationship_id from user_has_oi_relationship where user_id =:user_id
)
最后得到组名:
select id, name from chat_group
where id in (
--query 2
select chat_group_id from chat_group_has_oi_relationship
where oi_relationship_id in (
--query 1
select oi_relationship_id from user_has_oi_relationship where user_id =:user_id
)
)
sql语句的可读性很重要,所以你应该按照你的想法来写。数据库很聪明,可以将这些查询优化为可以快速运行的查询。只有当它开始成为性能瓶颈时,你才需要“考虑重写”。
顺便说一句,感谢您缩短问题的数据库结构。
关于php - 正确的 SQL 查询以访问用户可用的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23270140/