我从上表中需要的是:
1.某个id对应的所有用户详细信息。
2.他发布的帖子数量。
3.他拥有的关注者数量以及他正在关注的人数(followid=user1.user2 [User1 is followin user2]。
4.假设user1正在访问user2个人资料,我需要找出是否存在与user1和user2对应的followid,即follow_detail中的user1.user2。
我通过连接表(post_detail 和 user_detail)实现了 1 和 2,通过使用单独的查询(mysql 中的 When-then)实现了 3。 我想知道我是否可以在一个 SQL 查询中获得所有这些。这是由配置文件 API 返回的,因此使用多个查询来访问数据库应该不太好。 如果数据库设计不够好,无法在一个查询中获取上述所有数据,那么我可以更改它。
最佳答案
通过使用子查询,您可以将结果合并到单个查询中。这是否比多个简单查询更有效 - 我不太确定。您需要对其进行测试。
select ud.*,
(select count(*)
from post_detail where post_detail.user_id=ud.user_id) as post_count,
(select count(*)
from follow_detail where follow_detail.following=ud.user_id) as follower_count,
(select count(*)
from follow_detail where follow_detail.follow=ud.user.id and follow_detail.following=...) as follower_user
from user_detail ud
where ud.user_id=...
您需要提供用户 ID 来代替 ...
。我对最后一个子查询进行了相当多的猜测,因为不清楚您希望在那里看到什么。
关于mysql - SQL 连接。高效查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42956593/