我有3张这样的表
表1:UserInfo
#include "ioswrapper.h"
#import <UIKit/UIPasteboard.h>
ioswrapper::ioswrapper(QObject *parent):QObject(parent)
{
}
void ioswrapper::setPasteBoardString(const QString &paste)
{
UIPasteboard *pb = [UIPasteboard generalPasteboard];
if (pb) {
const char *str = paste.toUtf8().data();
NSString *text = [NSString stringWithCString:(const char *)str
encoding:(NSStringEncoding)NSUTF8StringEncoding];
if (text)
pb.string = text;
}
}
user_id userName
表2:帖子
123 userOne
user_id postContent
表3:LikePost
123 This is test message
user_id likesPostId
我想运行一个查询来获取这3个表中的帖子喜欢,帖子和用户信息的总数。
我可以为每个人执行此操作,例如在Post表中:
123 This is test message
和SELECT COUNT(*) FROM Post WHERE Post.user_id = '123'
有人在1个查询中有更好的解决方案吗?非常感谢你!
答案 0 :(得分:1)
使用类似这样的结构化查询(带子查询)。
SELECT u.user_id, u.userName, p.num postcount, l.num likecount
FROM UserInfo u
LEFT JOIN (
SELECT COUNT(*) num,
user_id
FROM Post
GROUP BY user_id
) p ON u.user_id = p.user_id
LEFT JOIN (
SELECT COUNT(*) num,
user_id
FROM LikePost
GROUP BY user_id
) l ON u.user_id = l.user_id
这里发生了什么?这两个子查询,例如
SELECT COUNT(*) num,
user_id
FROM LikePost
GROUP BY user_id
每个user_id生成一个零行或一行的虚拟表,显示每个user_id的计数。然后,将这些虚拟表连接到UserInfo表。
使用LEFT JOIN
,因为普通的内置JOIN
会抑制缺少帖子或喜欢的用户。
答案 1 :(得分:0)
试试这个
SELECT ui.userName,Count(p.*),
Count(lp.*) as TotalPostLikes
FROM UserInfo ui
INNER JOIN Post p on p.user_id=ui.user_id
INNER JOIN LikePost lp on lp.user_id=ui.user_id
WHERE ui.user_id = '123'
GROUP BY ui.userName
如果您想在帖子上选择用户名,发布和喜欢,请尝试以下
SELECT ui.userName,p.postContent as PostContent,
(SELECT COUNT(lp.user_id) FROM LikePost lp
WHERE lp.user_id=ui.user_id) as Likes,
(SELECT COUNT(_p .user_id) FROM Post _p
WHERE _p .user_id=ui.user_id) as TotalPosts
FROM UserInfo ui
INNER JOIN Post p on p.user_id=ui.user_id
WHERE ui.user_id = '123'
答案 2 :(得分:0)
是的,您可以使用leftjoin
上的Post
和下面的LikePost
在一个查询中执行此操作
SELECT COUNT(*),User.userName FROM UserInfo as User
leftjoin Post as Post on Post.user_id = User.user_id
leftjoin LikePost as LikePost on LikePost.user_id = User.user_id
where Post.user_id = 123
group by Post.user_id