php - 正确的 SQL 查询以访问用户可用的组

标签 php mysql sql

我按以下方式设置了一系列表格(为了便于阅读,它们已被简化):

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/

相关文章:

php - Try-Catch 未捕获自定义异常类型

php - 无法使用反序列化函数从序列化数组获取数据

mysql - 在MySQL中实现以下操作的更好方法?

javascript - 如何阻止我的代码异步运行?

mysql更新表设置column3其中table1.column1像concat ('%',table2.column2 ,'%')

mysql - 查询以相同的方式修改所有行的记录

用于获取 Youtube API 2.0 上传视频的访问 token 的 PHP google API 服务帐户

PHP Rename() 删除 Windows 中的所有者属性?

sql - 非 root 用户在 Linux 上安装 Firebird

sql - 查找与 iSeries 的特定 JDBC SQL 连接的实际作业号?