所以我对MySQL并不了解,但是我听说过有关观点的内容,而且我试图惹恼他们。
基本上我想做的是
查看表格 forum_posts ,计算每个用户发布的帖子数量
为每个用户查询 forum_users 以获取每一列并添加到视图中
我不知道该顺序是否在性能方面是正确的,但最终的观点在理论上看起来应该是
我设法通过使用以下代码
来获得帖子计数 SELECT
IFNULL(a.UId,-1) AS UId,
IFNULL(a.UName,'Unknown') AS UName,
postsquery.Posts AS UPosts,
IFNULL(a.UPosts,-1) AS UFakePosts
FROM
(
SELECT p.PId, p.PAuthorId, COUNT(p1.PAuthorId) as Posts
FROM forum_posts AS p
LEFT JOIN forum_posts AS p1 ON p1.PId = p.PId
GROUP BY p.PAuthorId
)
AS postsquery
LEFT JOIN forum_users AS a ON postsquery.PAuthorId = a.UId
ORDER BY postsquery.Posts DESC
但获取线程没有成功,我可以同时获得另一个但不能同时获得两个。
我也试过这个
SELECT IFNULL(a.UId,-1) AS UId,
IFNULL(a.UName,'Unknown') AS UName,
postsquery.Posts AS UPosts,
threadsquery.Threads AS UThreads,
IFNULL(a.UPosts,-1) AS UFakePosts
FROM
(
SELECT p.PId, p.PAuthorId, COUNT(p.PAuthorId) as Posts
FROM forum_posts AS p
)
AS postsquery
LEFT JOIN forum_users AS a1 ON postsquery.PAuthorId = a1.UId,
(
SELECT t.TId, t.TAuthorId, COUNT(t.TAuthorId) as Threads
FROM forum_threads AS t
GROUP BY t.TAuthorId
)
AS threadsquery
LEFT JOIN forum_users AS a ON threadsquery.TAuthorId = a.UId
ORDER BY
postsquery.Posts DESC
.....但结果是错误的:
应该发生什么:
未知(我尚未删除的用户):1个帖子/ 0个帖子
User1:2个帖子/ 0个帖子
User2:1 post / 2 threads
User3:0帖子/ 0个帖子
如果我可以做另一种观点,但是对于线程来说,获得一些独特的海报和一些很酷的帖子,但一次只能做一件事。
结构应该很容易理解, U 代表用户, T 代表线程, P 代表帖子, D < / strong>日期等等。
答案 0 :(得分:1)
创建子选择以获取线程数:
LEFT JOIN
(
SELECT
TAuthorId,
COUNT(1) as thread_count
FROM
forum_threads
GROUP BY
TAuthorId
) threads ON
threads.TAuthorId = postsquery.PAuthorId
然后选择该列:
IFNULL(threads.thread_count, 0) as thread_count
全部放在一起:
SELECT IFNULL(a.UId,-1) AS UId, IFNULL(a.UName,'Unknown') AS UName, IFNULL(postsquery.Posts, 0) AS UPosts, IFNULL(threads.thread_count, 0) as thread_count, IFNULL(a.UPosts,-1) AS UFakePosts
FROM
(
SELECT p.PId, p.PAuthorId, COUNT(p1.PAuthorId) as Posts
FROM forum_posts AS p
LEFT JOIN forum_posts AS p1 ON p1.PId = p.PId
GROUP BY p.PAuthorId
)
AS postsquery
LEFT JOIN forum_users AS a ON postsquery.PAuthorId = a.UId
LEFT JOIN
(
SELECT
TAuthorId,
COUNT(1) as thread_count
FROM
forum_threads
GROUP BY
TAuthorId
) threads ON
threads.TAuthorId = postsquery.PAuthorId
ORDER BY
postsquery.Posts DESC